[英]pandas dataframe check specific columns for same values
有沒有一種方法可以檢查和匯總特定數據框列中的相同值。
例如在以下數據框中
column name 1, 2, 3, 4, 5
-------------
a, g, h, t, j
b, a, o, a, g
c, j, w, e, q
d, b, d, q, i
比較列1和2時,相同值的總和為2(a和b)
謝謝
您可以使用isin
和sum
實現此目的:
In [96]:
import pandas as pd
import io
t="""1, 2, 3, 4, 5
a, g, h, t, j
b, a, o, a, g
c, j, w, e, q
d, b, d, q, i"""
df = pd.read_csv(io.StringIO(t), sep=',\s+')
df
Out[96]:
1 2 3 4 5
0 a g h t j
1 b a o a g
2 c j w e q
3 d b d q i
In [100]:
df['1'].isin(df['2']).sum()
Out[100]:
2
isin
將產生一個布爾序列,在布爾序列上調用sum會將True
和False
分別轉換為1
和0
:
In [101]:
df['1'].isin(df['2'])
Out[101]:
0 True
1 True
2 False
3 False
Name: 1, dtype: bool
編輯
要檢查並計算所有感興趣的列中存在的值的數量,請執行以下操作,請注意,對於您的數據集,所有列中都沒有存在的值:
In [123]:
df.ix[:, :'4'].apply(lambda x: x.isin(df['1'])).all(axis=1).sum()
Out[123]:
0
分解以上內容將顯示每個步驟在做什么:
In [124]:
df.ix[:, :'4'].apply(lambda x: x.isin(df['1']))
Out[124]:
1 2 3 4
0 True False False False
1 True True False True
2 True False False False
3 True True True False
In [125]:
df.ix[:, :'4'].apply(lambda x: x.isin(df['1'])).all(axis=1)
Out[125]:
0 False
1 False
2 False
3 False
dtype: bool
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.