繁体   English   中英

如何用值满足条件的列名填充pandas数据框中的列?

[英]How populate column in pandas dataframe with column names where value meets condition?

我需要在数据框中填充满足指定条件的列名的新列。 在此示例中,它> 1

我尝试遍历有问题的列(这是df.columns的子集),但是没有提供所需的输出。

df = pd.DataFrame([
    [1, 0, 2, 2],
    [1, 1, 0, 0],
    [0, 2, 3, 2],
    [2, 2, 1, 1]],
  columns=['col1', 'col2', 'col3', 'col4'])
cols = df.columns[:-1]
df['d'] = ''
for col in cols:
    df.loc[df[col] > 1, 'd'] = col

电流输出:

out = pd.DataFrame([
    [1, 0, 2, 2, 'col3'],
    [1, 1, 0, 0, ''],
    [0, 2, 3, 2, 'col3'],
    [2, 2, 1, 1, 'col2']],
    columns=['col1', 'col2', 'col3', 'col4', 'd'])

我需要的是有关满足该条件的所有列的信息,因此输出如下:

out = pd.DataFrame([
    [1, 0, 2, 2, 'col3'],
    [1, 1, 0, 0, ''],
    [0, 2, 3, 2, 'col2,col3'],
    [2, 2, 1, 1, 'col1,col2']],
    columns=['col1', 'col2', 'col3', 'col4', 'd'])

任何帮助,将不胜感激。

 df['d'] = (df.iloc[:,:-1] > 1).apply(lambda x: ','.join([col for cond,col in zip(x,df.columns) if cond]), axis=1)

结果:

   col1  col2  col3  col4          d
0     1     0     2     2       col3
1     1     1     0     0           
2     0     2     3     2  col2,col3
3     2     2     1     1  col1,col2

尝试以下代码段。

import pandas as pd
import numpy as np
df = pd.DataFrame([
    [1, 0, 2, 2],
    [1, 1, 0, 0],
    [0, 2, 3, 2],
    [2, 2, 1, 1]],
  columns=['col1', 'col2', 'col3', 'col4'])
# cols = df.columns[:-1]

df1 = df.iloc[:,:-1]
df1['threshold']=1

df2 = df1.drop('threshold', 1).gt(df1['threshold'], 0)
df2 = df2.apply(lambda x: ', '.join(x.index[x]),axis=1)

df['d']=df2

print df

输出:

   col1  col2  col3  col4           d
0     1     0     2     2        col3
1     1     1     0     0            
2     0     2     3     2  col2, col3
3     2     2     1     1  col1, col2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM