如果我具有以下数据框:
import pandas as pd
df = pd.DataFrame({"id": ['01', '02', '03', '04'], "A":["foo", "foo", "foo", "bar"], "B":[0,1,1,1], "C":["A","A","B","A"]})
id A B C
0 01 foo 0 A
1 02 foo 1 A
2 03 foo 1 B
3 04 bar 1 A
如果A列中的所有值都相同,我想将所有行都放在一行中,如何用熊猫呢?谢谢。
id A B C id A B C id A B C
0 01 foo 0 A 02 foo 1 A 03 foo 1 B
1 04 bar 1 A
答案 0 :(得分:1)
我认为以下工作有效:
new_df = (df.groupby('A',as_index=False,sort=False)
.apply(lambda x: pd.Series(x.values.flatten()))
.unstack())
new_df.columns = pd.np.tile(df.columns,len(new_df.columns)//len(df.columns))
>>> new_df
id A B C id A B C id A B C
0 01 foo 0 A 02 foo 1 A 03 foo 1 B
1 04 bar 1 A None None None None None None None None