简体   繁体   中英

create a list with pairs from a column in pandas

I have a column with pairs like these

id pairs
1 a,b,c
2 b,d
3 a
4 d,e
5 g,h
6 a,h
7 f,d
8 o,p

I want to have these output

[('ca', 'b'), ('a', 'c'),('b','c'),('b','d'),('d','e'),('g','h'),('a','h'),('f','d'),('o','p')]

I did these, but not the desired solution

for pair in combinations([df['pairs']], 2):
print(pairs)

any suggestions?

try this

pairs = []

for row in df['pairs']:
    row_list = row.split(',')
    for pair in combinations(row_list, 2):
        pairs.append(pair)

print(pairs)

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.

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