如何从熊猫数据框中选择特定的列项目作为列表?

时间:2018-07-10 07:14:49

标签: python pandas numpy dataframe series

我有一个像这样的数据框:

var element = $$('.someCss')[0];
element.click();

如何将其转换为这种形式(不考虑出现的所有零):

  A  B  C   D 
---------------
0  A  0  C  D
1  A  0  C  D
2  0  B  C  0
3  A  0  0  D
4  0  B  C  0
5  A  0  0  0

最后进入一系列项目:

   A  B  C  D    E
----------------------
0  A  0  C  D  [A,C,D]
1  A  0  C  D  [A,C,D]
2  0  A  C  0  [A,C]
3  A  0  0  D  [A,D]
4  0  A  C  0  [A,C]
5  A  0  0  0  [A]

1 个答案:

答案 0 :(得分:4)

结合使用嵌套列表推导和过滤0

#if 0 is number change '0' to 0
df['E'] = [[y for y in x if y != '0'] for x in df.values.tolist()]
print (df)
   A  B  C  D          E
0  A  0  C  D  [A, C, D]
1  A  0  C  D  [A, C, D]
2  0  B  C  0     [B, C]
3  A  0  0  D     [A, D]
4  0  B  C  0     [B, C]
5  A  0  0  0        [A]

对于set s:

s = [set([y for y in x if y != '0']) for x in df.values.tolist()]
print (s)
[{'A', 'D', 'C'}, {'A', 'D', 'C'}, {'C', 'B'}, {'A', 'D'}, {'C', 'B'}, {'A'}]