Reshape levels of a column (long) into new columns (wide)
Date : March 29 2020, 07:55 AM
may help you . I want to take the levels of a column in one DF and add each level as a new column in a new DF. Here is a toy dataset showing the source and ideal target DFs. require(reshape2)
mydat <- recast(test_data,hour~ride)
mydat
hour A B C
1 1 1 0 1
2 2 0 1 0
3 3 2 1 0
# 2nd part
for(i in 2:ncol(mydat)){
for(ii in 1:nrow(mydat)){
if(mydat[ii,i] > 0) {mydat[ii,i] <- 1}
}
}
hour A B C
1 1 1 0 1
2 2 0 1 0
3 3 1 1 0
|
reshape pandas wide column to long
Date : March 29 2020, 07:55 AM
will help you If possible one output column for teams use lreshape: df = pd.lreshape(df, {'t':['t1','t2']})
print (df)
buyprice sellprice tdate tno t
0 10 20 2017 1 teamA
1 5 10 2017 2 teamB
2 10 20 2017 1 teamB
3 5 10 2017 2 teamA
df = pd.concat([df.drop('t2', axis=1), df.drop('t1', axis=1)], ignore_index=True)
.reindex_axis(df.columns, 1)
.sort_values(['tno','tdate'])
print (df)
tno tdate buyprice sellprice t1 t2
0 1 2017 10 20 teamA NaN
2 1 2017 10 20 NaN teamB
1 2 2017 5 10 teamB NaN
3 2 2017 5 10 NaN teamA
|
R: reshape dataframe from wide to long format based on compound column names
Date : March 29 2020, 07:55 AM
I hope this helps . Yes you can do this with tidyverse ! You were close, you need to gather, then separate, then spread. new_df <- mydf %>%
gather(set, vars, 3:6) %>%
separate(set, into = c('set', 'var'), sep = "_") %>%
spread(var, vars)
|
R wide to long reshape with column names
Date : October 29 2020, 05:01 AM
wish help you to fix your issue We can gather into 'long' format, then separate the 'key' column into two by splitting before the numeric part, spread it to 'wide' and change the 'key1' column to row names library(tidyverse)
gather(df1) %>%
separate(key, into = c('key1', 'key2'), sep="(?=\\d)") %>%
spread(key2, value) %>%
column_to_rownames('key1')
# 1 2
#A 10 5
#B 11 5
#C 21 10
df1 <- structure(list(A1 = 10L, A2 = 5L, B1 = 11L, B2 = 5L, C1 = 21L,
C2 = 10L), class = "data.frame", row.names = c(NA, -1L))
|
Reshape DataFrame from long to wide along one column
Tag : python , By : adbanginwar
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I am looking for a way to reconfigure Table A show below into Table B. , You can set the index appropriately and then unstack: df
type x1 x2 x3
0 A 4 6 9
1 A 7 4 1
2 A 9 6 2
3 B 1 3 8
4 B 2 7 9
res = (df.set_index(['type', df.groupby('type').cumcount()])
.unstack()
.sort_index(level=-1, axis=1))
res.columns = res.columns.map(lambda x: x[0] + "'" * int(x[1]))
res
x1 x2 x3 x1' x2' x3' x1'' x2'' x3''
type
A 4.0 6.0 9.0 7.0 4.0 1.0 9.0 6.0 2.0
B 1.0 3.0 8.0 2.0 7.0 9.0 NaN NaN NaN
|