有没有一种方法可以检查和汇总特定数据框列中的相同值。

例如在以下数据框中

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)

谢谢

最佳答案

您可以使用isinsum实现此目的:

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会将TrueFalse分别转换为10

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

10-06 13:37
查看更多