數據幀熊貓:如何比較數據框中的列與行列的列與熊貓(不適用於循環)?
df = pd.DataFrame({'A': [['gener'], ['gener'], ['system'], ['system'], ['gutter'], ['gutter'], ['gutter'], ['gutter'], ['gutter'], ['gutter'], ['aluminum'], ['aluminum'], ['aluminum'], ['aluminum'], ['aluminum'], ['aluminum'], ['aluminum'], ['aluminum'], ['aluminum'], ['aluminum', 'toledo']], 'B': [['gutter'], ['gutter'], ['gutter', 'system'], ['gutter', 'guard', 'system'], ['ohio', 'gutter'], ['gutter', 'toledo'], ['toledo', 'gutter'], ['gutter'], ['gutter'], ['gutter'], ['how', 'to', 'instal', 'aluminum', 'gutter'], ['aluminum', 'gutter'], ['aluminum', 'gutter', 'color'], ['aluminum', 'gutter'], ['aluminum', 'gutter', 'adrian', 'ohio'], ['aluminum', 'gutter', 'bowl', 'green', 'ohio'], ['aluminum', 'gutter', 'maume', 'ohio'], ['aluminum', 'gutter', 'perrysburg', 'ohio'], ['aluminum', 'gutter', 'tecumseh', 'ohio'], ['aluminum', 'gutter', 'toledo', 'ohio']]}, columns=['A', 'B'])
是什麼樣子
我有名單的兩列的數據幀。
A B
0 [gener] [gutter]
1 [gener] [gutter]
2 [system] [gutter, system]
3 [system] [gutter, guard, system]
4 [gutter] [ohio, gutter]
5 [gutter] [gutter, toledo]
6 [gutter] [toledo, gutter]
7 [gutter] [gutter]
8 [gutter] [gutter]
9 [gutter] [gutter]
10 [aluminum] [how, to, instal, aluminum, gutter]
11 [aluminum] [aluminum, gutter]
12 [aluminum] [aluminum, gutter, color]
13 [aluminum] [aluminum, gutter]
14 [aluminum] [aluminum, gutter, adrian, ohio]
15 [aluminum] [aluminum, gutter, bowl, green, ohio]
16 [aluminum] [aluminum, gutter, maume, ohio]
17 [aluminum] [aluminum, gutter, perrysburg, ohio]
18 [aluminum] [aluminum, gutter, tecumseh, ohio]
19 [aluminum, toledo] [aluminum, gutter, toledo, ohio]
問題
如果我有名單之列,是有一個熊貓功能,讓我列出的整個陣列上運行檢查交集,並返回一個布爾值或相交的值一個新的系列?
例如,我想熊貓有這樣的一個等價的:
def intersection(df, col1, col2, return_type='boolean'):
if return_type == 'boolean':
df = df[[col1, col2]]
s = []
for idx in df.iterrows():
s.append(any([phrase in idx[1][0] for phrase in idx[1][1]]))
S = pd.Series(s)
return S
elif return_type == 'word':
df = df[[col1, col2]]
s = []
for idx in df.iterrows():
s.append(', '.join([word for word in list(set(idx[1][0]).intersection(set(idx[1][1])))]))
S = pd.Series(s)
return S
#Create column C in df
df['C'] = intersection(df, 'A', 'B', 'word')
...而無需編寫我自己的函數或訴諸for循環。我覺得必須有一種更簡單的方法來比較同一行上的兩列中的列表以查看它們是否相交。
我可以for
循環做,但它的醜陋給我
for
環路返回一個boolean
系列:
for idx in df.iterrows():
any([phrase in idx[1][0] for phrase in idx[1][1]])
產地:
False
False
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
True
或者,找到使用set
s相交的單詞:
for idx in df.iterrows():
', '.join([word for word in list(set(idx[1][0]).intersection(set(idx[1][1])))])
''
''
'system'
'system'
'gutter'
'gutter'
'gutter'
'gutter'
'gutter'
'gutter'
'aluminum'
'aluminum'
'aluminum'
'aluminum'
'aluminum'
'aluminum'
'aluminum'
'aluminum'
'aluminum'
'toledo, aluminum'
準確地說,我希望能夠從這個問題中獲得單行和知識。謝謝! – Jarad