python - 匹配列中的值并返回 pandas | 中的另一列Python

标签 python string pandas dataframe

我有一个包含两列的输入文件1(制表符分隔):

c1\tc2
aaa\t232 65 19 32
bbew\t32 22 20
jhsi\t986 1 32 463 221

输入文件2,其中有一列:

c1
19
1
32
277

我想要的是在file1中搜索file2中的元素,并在c1中返回相应的值。如果有多个匹配值,则将所有值一起返回在一列中。

输出文件应该是这样的:

19       aaa
1        jhsi
32       aaa bbew jhsi
277      

277 将保留为空,因为它不存在。

任何建议都会有帮助。

最佳答案

这不容易矢量化。为了提高性能,我建议您在将数据放入 Pandas 数据帧之前执行转换。这是使用 collections.defaultdict 的解决方案:

# use set for O(1) lookup
scope_set = set(df2['c1'])

# initialise defualtdict of lists
dd = defaultdict(list)

# iterate and create dictionary mapping numbers to keys
for row in df1.itertuples(index=False):
    for num in map(int, row.c2.split()):
        if num in scope_set:
            dd[num].append(row.c1)

# construct dataframe from defaultdict
df = pd.DataFrame({'num': list(dd), 'keys': list(map(' '.join, dd.values()))})

# reindex to include blanks
df = df.set_index('num').reindex(sorted(scope_set)).reset_index()

结果

print(df)

   num           keys
0    1           jhsi
1   19            aaa
2   32  aaa bbew jhsi
3  277            NaN

设置

from io import StringIO
from collections import defaultdict

file1 = StringIO("""c1\tc2
aaa\t232 65 19 32
bbew\t32 22 20
jhsi\t986 1 32 463 221""")

file2 = StringIO("""c1
19
1
32
277""")

df1 = pd.read_csv(file1, sep='\t')
df2 = pd.read_csv(file2)

关于python - 匹配列中的值并返回 pandas | 中的另一列Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52705423/

相关文章:

swift - 在 Swift 3 中将字符串转换为整数

python - pandas to_csv 参数 float_format 为百分比

python - 为什么 Pandas .fillna() 不在 DataFrame 中填充值?

python - Spark ML 中的维度不匹配错误

python - Keras Maxpooling2d 层给出 ValueError

python - 如何使用绑定(bind)事件立即在组合框中打印文本?

python - 本地托管的 Google App Engine(WebApp 框架/BigTable)

string - 包含集合中出现次数最多的字符串的最短字符串

string - 首字母大写Lua

Python Pandas 分配/计算 bool 列的位置