Transpose a Data Frame

How do I transpose dataframe in pandas without index?

You can set the index to your first column (or in general, the column you want to use as as index) in your dataframe first, then transpose the dataframe. For example if the column you want to use as index is 'Attribute', you can do:

df.set_index('Attribute',inplace=True)
df.transpose()

Or

df.set_index('Attribute').T

Transposing a data frame

data <- as.data.frame(t(data))

This ensures that the numeric values are not converted to string values.

Transpose columns to rows in R dataframe

We may use pivot_longer

library(tidyr)
pivot_longer(df, cols = starts_with('cheese'),
names_to = c("product", ".value"), names_sep = "\\.",
values_transform = list(kg = as.integer))

-output

# A tibble: 6 × 4
level1 column.other product kg
<chr> <chr> <chr> <int>
1 A yes cheese1 58
2 A yes cheese2 11
3 B yes cheese1 63
4 B yes cheese2 22
5 C yes cheese1 33
6 C yes cheese2 20

How to transpose a data frame in R in a way that the elements of a character variable become columns in the new data frame

We can use pivot_wider

library(dplyr)
library(tidyr)
df %>%
pivot_wider(names_from = Type, values_from = Value, values_fill = 0)

-output

# A tibble: 3 × 3
ID A B
<dbl> <dbl> <dbl>
1 1 2.5 8
2 2 10 0
3 3 7 0

data

df <- data.frame(ID, Type, Value)

What is the best way to transpose a data.frame in R and to set one of the columns to be the header for the new transposed table?

Well you could do it in 2 steps by using

# Transpose table YOU WANT
fooData.T <- t(fooData[,2:ncol(fooData)])

# Set the column headings from the first column in the original table
colnames(fooData.T) <- fooData[,1]

The result being a matrix which you're probably aware of, that's due to class issues when transposing. I don't think there will be a single line way to do this given the lack of naming abilities in the transpose step.



Related Topics



Leave a reply



Submit