【问题标题】:How to create a list according to columns values如何根据列值创建列表
【发布时间】:2023-02-14 15:15:49
【问题描述】:

我有这个数据框:

Text     feat1   feat2   feat3    feat4
string1    1       1       0        0
string2    0       0       0        1
string3    0       0       0        0

我想以这种方式创建另外 2 个列:

Text     feat1   feat2   feat3    feat4     all_feat            count_feat
string1    1       1       0        0       ["feat1","feat2"]       2
string2    0       0       0        1       ["feat4"]               1
string3    0       0       0        0       []                      0

在 Python 中执行此操作的最佳方法是什么?

列名可以是任何字符串。

【问题讨论】:

  • 我假设您使用的是 Pandas,对吗?
  • 是的!使用熊猫。

标签: python pandas


【解决方案1】:

您可以使用:

df1 = (df.filter(like='feat').mul(df.columns[1:]).apply(lambda x: [i for i in x if i], axis=1)
         .to_frame('all_feat').assign(count=lambda x: x['all_feat'].str.len()))
df = pd.concat([df, df1], axis=1)
print(df)

# Output
      Text  feat1  feat2  feat3  feat4        all_feat  count
0  string1      1      1      0      0  [feat1, feat2]      2
1  string2      0      0      0      1         [feat4]      1
2  string3      0      0      0      0              []      0

【讨论】:

    【解决方案2】:

    您可以使用groupby:

    df2 = df.filter(like='feat').melt(ignore_index=False)
    g = df2.groupby(level=0)
    
    df['all_feat'] = g.apply(lambda g: list(g.loc[g['value'].eq(1), 'variable']))
    df['count_feat'] = g['value'].sum()
    

    输出:

          Text  feat1  feat2  feat3  feat4        all_feat  count_feat
    0  string1      1      1      0      0  [feat1, feat2]           2
    1  string2      0      0      0      1         [feat4]           1
    2  string3      0      0      0      0              []           0
    

    【讨论】:

    • g = df.filter(like='feat').melt(ignore_index=False).groupby(level=0)
    • 不错@Corralien,我从来没有注意过这个选项,谢谢!
    【解决方案3】:
    col1=df1.set_index("Text").apply(lambda ss:ss.loc[ss>0].index.tolist(),axis=1).reset_index(drop=True)
    col2=df1.set_index("Text").apply(lambda ss:ss.loc[ss>0].size,axis=1).reset_index(drop=True)
    df1.assign(all_feat=col1,count_feat=col2)
    

    输出

          Text  feat1  feat2  feat3  feat4        all_feat  count
    0  string1      1      1      0      0  [feat1, feat2]      2
    1  string2      0      0      0      1         [feat4]      1
    2  string3      0      0      0      0              []      0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      • 1970-01-01
      • 1970-01-01
      • 2019-12-01
      • 1970-01-01
      相关资源
      最近更新 更多