2

我有一个熊猫数据框df的形式:

     Col1      Col2      Col3      Col4

0    True      False     True      False
1    False     False     False     False
2    False     True      False     False
3    True      True      True      True

这里 True 和 False 是布尔值。

我正在尝试生成一个新的熊猫数据框 new_df,它应该如下所示:

     Matched_Cols

0    [Col1, Col3]
1    []
2    [Col2]
3    [Col1, Col2, Col3, Col4]

实现这一目标的最有效方法是什么?

4

4 回答 4

4

方法#1

这是数组数据处理 -

def iter_accum(df):
    c = df.columns.values.astype(str)
    return pd.DataFrame({'Matched_Cols':[c[i] for i in df.values]})

样本输出 -

In [41]: df
Out[41]: 
    Col1   Col2   Col3   Col4
0   True  False   True  False
1  False  False  False  False
2  False   True  False  False
3   True   True   True   True

In [42]: iter_accum(df)
Out[42]: 
               Matched_Cols
0              [Col1, Col3]
1                        []
2                    [Col2]
3  [Col1, Col2, Col3, Col4]

方法#2

另一个对数组数据进行切片和一些布尔索引 -

def slice_accum(df):
    c = df.columns.values.astype(str)
    a = df.values
    vals = np.broadcast_to(c,a.shape)[a]
    I = np.r_[0,a.sum(1).cumsum()]
    ac = []
    for (i,j) in zip(I[:-1],I[1:]):
        ac.append(vals[i:j])
    return pd.DataFrame({'Matched_Cols':ac})

基准测试

其他建议的解决方案 -

# @jezrael's soln-1
def jez1(df):
    return df.apply(lambda x: x.index[x].tolist(), axis=1)

# @jezrael's soln-2
def jez2(df):
    return df.dot(df.columns + ',').str.rstrip(',').str.split(',')

# @Shubham Sharma's soln
def Shubham1(df):
    return df.agg(lambda s: s.index[s].values, axis=1) 

# @sammywemmy's soln
def sammywemmy1(df):
    return pd.DataFrame({'Matched_Cols':[np.compress(x,y) for x,y in zip(df.to_numpy(),np.tile(df.columns,(len(df),1)))]})

使用benchit包(几个基准测试工具打包在一起;免责声明:我是它的作者)对建议的解决方案进行基准测试。

import benchit
funcs = [iter_accum,slice_accum,jez1,jez2,Shubham1,sammywemmy1]
in_ = {n:pd.DataFrame(np.random.rand(n,n)>0.5, columns=['Col'+str(i) for i in range(1,n+1)]) for n in [4,20,100,200,500,1000]}
t = benchit.timings(funcs, in_, input_name='Len')
t.rank()
t.plot(logx=True)

在此处输入图像描述

于 2020-06-01T07:46:34.077 回答
2

您可以过滤每行索引值,原始列名是什么DataFrame,然后转换为列表:

df['Matched_Cols'] = df.apply(lambda x: x.index[x].tolist(), axis=1)

或者使用DataFrame.dot带有分隔符的列名称进行矩阵乘法,删除最后一个分隔符值Series.str.rstrip和最后一次使用Series.str.split

df['Matched_Cols'] = df.dot(df.columns + ',').str.rstrip(',').str.split(',')

print (df)
    Col1   Col2   Col3   Col4              Matched_Cols
0   True  False   True  False              [Col1, Col3]
1  False  False  False  False                        []
2  False   True  False  False                    [Col2]
3   True   True   True   True  [Col1, Col2, Col3, Col4]
于 2020-06-01T07:35:36.693 回答
1

不必要的长:

df['Matched_Col'] = [np.compress(x,y) for x,y in zip(df.to_numpy(),np.tile(df.columns,(len(df),1)))]

Col1    Col2    Col3    Col4    Matched_Col
0   True    False   True    False   [Col1, Col3]
1   False   False   False   False   []
2   False   True    False   False   [Col2]
3   True    True    True    True    [Col1, Col2, Col3, Col4]
于 2020-06-01T07:47:48.920 回答
1

利用:

df['Matched_Cols'] = df.agg(lambda s: s.index[s].values, axis=1) 

结果:

   Col1   Col2   Col3   Col4               Matched_Cols

0   True  False   True  False              [Col1, Col3]
1  False  False  False  False                        []
2  False   True  False  False                    [Col2]
3   True   True   True   True  [Col1, Col2, Col3, Col4]
于 2020-06-01T08:02:17.133 回答