Python Pandas Groupby/Append columns
问题 This is my example dataframe: Index Param1 Param2 A 1 2 A 3 4 B 1 3 B 4 Nan C 2 4 What I would like to get is: Index Param1 Param2 Param3 Param4 A 1 2 3 4 B 1 3 4 C 2 4 What would be the best way to achieve it using pandas? Thanks in advance for your help. 回答1: You can use groupby with unstack: def f(x): return (pd.DataFrame(np.sort(x.values.ravel()))) df = df.groupby('Index')['Param1','Param2'].apply(f).unstack() df.columns = df.columns.droplevel(0) print (df) 0 1 2 3 Index A 1 2 3 4 B 1 3 4