[英]How to convert a list of variable numbers of “couples” to a two column dataframe?
如何從列表的共同作者列表中生成一個數據框,該列表具有兩列(auth1和auth2),每對一對一行?
coauthors = []
coauthors.append((("f","g"),("f","h"),("g","h"))) # combinations of f,g,h
coauthors.append((("i","j"),("i","k"),("i","l"),("j","k"),("j","l"),("l","k"))) # combinations of i,j,k,l
coauthors.append((("a","b"))) # combinations of a,b
for s in coauthors:
print(*s)
附帶問題:為什么上面的最后一行不是('a','b')而是ab?
您應該使用extend
而不是append
來構造原始列表:
coauthors = []
coauthors.extend((("f","g"),("f","h"),("g","h"))) # combinations of f,g,h
coauthors.extend((("i","j"),("i","k"),("i","l"),("j","k"),("j","l"),("l","k"))) # combinations of i,j,k,l
coauthors.extend((("a","b"),)) # combinations of a,b
這具有用傳遞的iterable的元素擴展原始列表的作用,而不是將傳遞的iterable作為原始列表的單個新元素附加。
還要注意,我在上面的最后一行中添加了一個逗號(以解決您的副問題中的問題)。 這是告訴Python您想通過extend
一個元組的元組(外部元組僅包含一個元組)。 沒有這個逗號,外括號將被忽略,Python認為您只傳遞了元組('a', 'b')
。
這給出了長度為2的10個元組的列表,而不是使用append
生成的嵌套結構。 從這里開始,創建DataFrame很容易:
import pandas as pd
df = pd.DataFrame(coauthors, columns=['auth1', 'auth2'])
贈送:
auth1 auth2
0 f g
1 f h
2 g h
3 i j
4 i k
5 i l
6 j k
7 j l
8 l k
9 a b
很難確定您是否具有這些值,或對組合進行硬編碼。 但是,如果使用itertools
這會容易得多。 創建一個列表列表,每個子列表都是您要從中創建配對的作者的分組,然后使用鏈和組合將所有配對放入一個DataFrame
import pandas as pd
from itertools import combinations, chain
groups = [['f', 'g', 'h'], ['i', 'j', 'k', 'l'], ['a', 'b']]
pd.DataFrame(chain.from_iterable([combinations(x, 2) for x in groups]),
columns=['auth1', 'auth2'])
auth1 auth2
0 f g
1 f h
2 g h
3 i j
4 i k
5 i l
6 j k
7 j l
8 k l
9 a b
如果還需要為每個組添加唯一的ID
,則可以連接一堆較小的DataFrames
:
pd.concat([
pd.DataFrame(data, columns=['auth1', 'auth2']).assign(id=gid)
for data,gid in zip([combinations(x, 2) for x in groups], range(len(groups)))
], ignore_index=True)
auth1 auth2 id
0 f g 0
1 f h 0
2 g h 0
3 i j 1
4 i k 1
5 i l 1
6 j k 1
7 j l 1
8 k l 1
9 a b 2
或者,您可以將內容解壓縮到3個元素列表的列表中, pd.DataFrame
一次調用pd.DataFrame
:
pd.DataFrame([[*z, gid] for data,gid in zip([combinations(x, 2) for x in groups], range(len(groups))) for z in data],
columns=['auth1', 'auth2', 'id'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.