计算多列python中的字符串实例

prm*_*lmu 6 python duplicates dataframe pandas

我有以下简单的数据框架

import pandas as pd
df = pd.DataFrame({'column_a': ['a', 'b', 'c', 'd', 'e'],
                   'column_b': ['b', 'x', 'y', 'c', 'z']})


      column_a column_b
0        a        b
1        b        x
2        c        y
3        d        c
4        e        z
Run Code Online (Sandbox Code Playgroud)

我想要显示两列中出现的字符串:

result = ("b", "c")
Run Code Online (Sandbox Code Playgroud)

谢谢

piR*_*red 7

intersection

这概括了任意数量的列.

set.intersection(*map(set, map(df.get, df)))

{'b', 'c'}
Run Code Online (Sandbox Code Playgroud)


T B*_*gis 5

使用python的set对象:

in_a = set(df.column_a)
in_b = set(df.column_b)
in_both = in_a.intersection(in_b)
Run Code Online (Sandbox Code Playgroud)

  • 也作为一个衬里工作:`result = set(df.column_a).intersection(df.column_b)` (2认同)