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
How to Use Facets With a Dual Y-Axis Ggplot
Concatenate Strings by Group With Dplyr
Read All Files in Directory and Apply Multiple Functions to Each Data Frame
Replace Na in Column With Value in Adjacent Column
How to Open CSV File in R When R Says "No Such File or Directory"
How to Unload a Package Without Restarting R
Calculating Statistics on Subsets of Data
Error: '\R' Is an Unrecognized Escape in Character String Starting "C:\R"
How to Change the Y-Axis Figures into Percentages in a Barplot
How to Tell What Is in One Vector and Not Another
How to Change the Order of Facet Labels in Ggplot (Custom Facet Wrap Labels)
Create a Data.Frame Where a Column Is a List
Subset a Dataframe Between 2 Dates
What Does .Sd Stand For in Data.Table in R
As.Date With Dates in Format M/D/Y in R
How to Move Cells With a Value Row-Wise to the Left in a Dataframe