我有一个包含两列的输入文件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/