python - 根据行中的数字将 Pandas 数据框列转换为列表

标签 python pandas dataframe transformation

我有一个这样的数据框:

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/

相关文章:

python - statsmodels - 打印 ARMA 拟合摘要会引发错误

python - 通过使用 for 循环更改一列来创建多个数据框?

python - 移动所有列的数据帧值以使其单调递增

python - Pandas read_table() 缺少行

python - 在 boost.python 中包装 MPI

python - 如何从时间戳中减去充满日期的 pandas.core.series.Series ,以找到每行日期与该时间戳日期的差异?

python - 有效循环 pandas 数据框

python - 删除数据框中的行数

python - 我可以使用集合理解从更大的字典列表中创建字典列表吗?

python - 在 Pandas 数据透视表中获取所有相应的最大值