我有一个这样的数据框:
Day Id Banana Apple
2020-01-01 1 1 1
2020-01-02 1 NaN 2
2020-01-03 2 2 2
如何将其转换为:
Day Id Banana Apple Products
2020-01-01 1 1 1 [Banana, Apple]
2020-01-02 1 NaN 2 [Apple, Apple]
2020-01-03 2 2 2 [Banana, Banana, Apple, Apple]
最佳答案
按 DataFrame.iloc
的位置选择所有没有前 2 列的列, 然后通过 DataFrame.stack
reshape , 按 Index.repeat
重复 MultiIndex
并聚合 list
:
s = df.iloc[:, 2:].stack()
df['Products'] = s[s.index.repeat(s)].reset_index().groupby(['level_0'])['level_1'].agg(list)
print (df)
Day Id Banana Apple Products
0 2020-01-01 1 1.0 1 [Banana, Apple]
1 2020-01-02 1 NaN 2 [Apple, Apple]
2 2020-01-03 2 2.0 2 [Banana, Banana, Apple, Apple]
或者使用带有重复列
名称且没有缺失值的自定义函数:
def f(x):
s = x.dropna()
return s.index.repeat(s).tolist()
df['Products'] = df.iloc[:, 2:].apply(f, axis=1)
print (df)
Day Id Banana Apple Products
0 2020-01-01 1 1.0 1 [Banana, Apple]
1 2020-01-02 1 NaN 2 [Apple, Apple]
2 2020-01-03 2 2.0 2 [Banana, Banana, Apple, Apple]
关于python - 根据行中的数字将 Pandas 数据框列转换为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60867835/