use*_*827 5 python dataframe pandas
我有以下数据帧:
pp b pp b
5 0.001464 6 0.001853
5 0.001459 6 0.001843
Run Code Online (Sandbox Code Playgroud)
有没有办法组合具有相同名称的列?我只想把它作为输出:
pp b
5 0.001464
5 0.001459
6 0.001853
6 0.001843
Run Code Online (Sandbox Code Playgroud)
尝试groupby使用轴 = 1
df.groupby(df.columns.values, axis=1).agg(lambda x: x.values.tolist()).sum().apply(pd.Series).T.sort_values('pp')
Out[320]:
b pp
0 0.001464 5.0
2 0.001459 5.0
1 0.001853 6.0
3 0.001843 6.0
Run Code Online (Sandbox Code Playgroud)
一种有趣的方式 wide_to_long
s=pd.Series(df.columns)
df.columns=df.columns+s.groupby(s).cumcount().astype(str)
pd.wide_to_long(df.reset_index(),stubnames=['pp','b'],i='index',j='drop',suffix='\d+')
Out[342]:
pp b
index drop
0 0 5 0.001464
1 0 5 0.001459
0 1 6 0.001853
1 1 6 0.001843
Run Code Online (Sandbox Code Playgroud)