我面临根据列值将列索引组合到新列中的问题。
0 1 2 3 4 5 all
0 0 0 4 5 0 0 [2,3]
1 0 2 0 0 0 1 [1,5]
2 0 0 0 0 0 0 []
3 3 0 0 4 5 0 [0,3,4]
4 0 0 0 0 1 0 [4]
我得到了0到5列,并想基于列中的非零值创建列“ all”。 我可以根据以下代码整理索引。但是我附加条件的努力失败了。请帮忙。
Xtrn['all'] = Xtrn.apply(lambda row: ','.join(row.index.astype(str)), axis=1)
答案 0 :(得分:1)
如果需要通过分隔符连接的值,请使用DataFrame.dot
和带有DataFrame.gt
的布尔掩码,以获取更大的值,例如0
并具有列名:
Xtrn['all'] = Xtrn.gt(0).dot(Xtrn.columns.astype(str) + ',').str[:-1]
print (Xtrn)
0 1 2 3 4 5 all
0 0 0 4 5 0 0 2,3
1 0 2 0 0 0 1 1,5
2 0 0 0 0 0 0
3 3 0 0 4 5 0 0,3,4
4 0 0 0 0 1 0 4
或者:
Xtrn['all'] = Xtrn.gt(0).dot(Xtrn.columns.astype(str) + ',').str.rstrip(',')
如果需要列表,请使用带有索引的列表理解:
cols = Xtrn.columns.to_numpy()
Xtrn['all'] = [cols[x].tolist() for x in Xtrn.gt(0).to_numpy()]
print (Xtrn)
0 1 2 3 4 5 all
0 0 0 4 5 0 0 [2, 3]
1 0 2 0 0 0 1 [1, 5]
2 0 0 0 0 0 0 []
3 3 0 0 4 5 0 [0, 3, 4]
4 0 0 0 0 1 0 [4]
Apply
解决方案是可行的,但是很慢,因此如果有很多行或性能很重要,建议不要这样做:
Xtrn['all'] = Xtrn.gt(0).apply(lambda row: ','.join(row.index[row].astype(str)), axis=1)
Xtrn['all'] = Xtrn.gt(0).apply(lambda row: row.index[row].tolist(), axis=1)
答案 1 :(得分:1)
您可以仅使用enumerate
来获取诸如
>>> df
0 1 2 3 4 5
0 0 0 4 5 0 0
1 0 2 0 0 0 1
2 0 0 0 0 0 0
3 3 0 0 4 5 0
>>>
>>>
>>> df['all'] = df.apply(lambda x: [idx for idx,v in enumerate(x) if v > 0], axis=1)
>>> df
0 1 2 3 4 5 all
0 0 0 4 5 0 0 [2, 3]
1 0 2 0 0 0 1 [1, 5]
2 0 0 0 0 0 0 []
3 3 0 0 4 5 0 [0, 3, 4]
>>>
答案 2 :(得分:1)
有些不同
df.apply(lambda x : x.index[x > 0].tolist(), axis=1)
Out[316]:
0 [2, 3]
1 [1, 5]
2 []
3 [0, 3, 4]
4 [4]
dtype: object