如何更改某些行以在数据框中列出?

时间:2019-06-05 09:30:42

标签: python pandas dataframe

我在df中有一些行,它是7天数据,具有某些(可能是3-5个)功能,我想根据功能将7天数组合并到一个列表中。

现在是循环唯一列以应用列表函数,但效率不高。

如果直接加载df,df会自动在重复的列中添加数字后缀,但concat不会

df1 = pd.DataFrame({"userId":["u1", "u2", "u3", "u4"], "a":[1,2,3,4], "b":[2,3,4,5], "c":[3,4,5,6], "d":[4,5,6,7]}).set_index('userId')
df2 = pd.DataFrame({"userId":["u1", "u2", "u3", "u4"], "a":[4,0,1,1], "b":[2,4,4,5], "c":[3,6,5,6], "d":[4,5,6,9]}).set_index('userId')
df3 = pd.DataFrame({"userId":["u1", "u2", "u3", "u4"], "a":[1,2,5,4], "b":[2,1,4,5], "c":[3,2,5,6], "d":[4,3,4,7]}).set_index('userId')
df = pd.concat([df1,df2,df3], axis=1, sort=False)
df_new = pd.DataFrame()
columns = df.columns.unique().tolist()
for columns_name in columns:
    df_new[columns_name] = df[columns_name].apply(lambda x: x.tolist(), axis=1)
print(df_new)
                a          b          c          d
userId
u1      [1, 4, 1]  [2, 2, 2]  [3, 3, 3]  [4, 4, 4]
u2      [2, 0, 2]  [3, 4, 1]  [4, 6, 2]  [5, 5, 3]
u3      [3, 1, 5]  [4, 4, 4]  [5, 5, 5]  [6, 6, 4]
u4      [4, 1, 4]  [5, 5, 5]  [6, 6, 6]  [7, 9, 7]

更改是为了应用它,我想找到更有效的方法,例如groupby,eval,applymap或其他方法。

1 个答案:

答案 0 :(得分:1)

在列名中使用GroupBy.agg

df1 = df.groupby(level=0, axis=1).agg(lambda x: x.tolist())
print (df1)
                a          b          c          d
userId                                            
u1      [1, 4, 1]  [2, 2, 2]  [3, 3, 3]  [4, 4, 4]
u2      [2, 0, 2]  [3, 4, 1]  [4, 6, 2]  [5, 5, 3]
u3      [3, 1, 5]  [4, 4, 4]  [5, 5, 5]  [6, 6, 4]
u4      [4, 1, 4]  [5, 5, 5]  [6, 6, 6]  [7, 9, 7]