I have a dataframe like this :
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
How to convert it into this form (All zeros appearing are not considered) :
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]
And finally into a set of items like :
[{A,C,D},{A,C,D},{A,C},{A,D},{A,C},{A}]
Use nested list comprehension with filtering 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]
And for 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'}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.