[英]Using Pandas Lambda to compare two text strings from different columns
[英]python, compare strings in columns located in two different text files
我有2个文本文件,分别是“ animals.txt”和“ colors.txt”,其中每行中的2个字符串由一个制表符分隔。
“ animals.txt”
12345 dog
23456 sheep
34567 pig
“ colors.txt”
34567 pink
12345 black
23456 white
我想编写以下Python代码:
输出1,其中包含animals.txt行和colors.txt第二列中与查询值相对应的值(12345):
12345 dog black
23456 sheep white
34567 pig pink
output2包含colors.txt第二列中与查询值相对应的值的列表(12345,然后是23456,然后是34567)):
black
white
pink
如果顺序无关紧要,这将成为一个非常简单的问题:
with open('animals.txt') as f1, open('colors.txt') as f2:
animals = {}
for line in f1:
animal_id, animal_type = line.split('\t')
animals[animal_id] = animal_type
#animals = dict(map(str.split,f1)) would work instead of the above loop if there are no multi-word entries.
colors={}
for line in f2:
color_id, color_name = line.split('\t')
colors[color_id] = color_name
#colors = dict(map(str.split,f2)) would work instead of the above loop if there are no multi-word entries.
#Thanks @Sven for pointing this out.
common=set(animals.keys()) & set(colors.keys()) #set intersection.
with open('output1.txt','w') as f1, open('output2.txt','w') as f2:
for i in common: #sorted(common,key=int) #would work here to sort.
f1.write("%s\t%s\t%s\n"%(i,animals[i],colors[i])
f2.write("%s"%colors[i])
您可能可以通过defaultdict
更优雅地执行此操作,在遇到特定键时将其追加到列表,然后在编写时测试在输出之前列表的长度为2,但是,我不是深信这种方法更好。
您需要使用python吗? 如果您正在使用bash并且输入未排序,请执行以下操作:
$ join -t $'\t' <( sort animals.txt ) <( sort colors.txt ) > output1
$ cut -f 3 output1 > output2
如果您没有支持进程替换的外壳,请对输入文件进行排序并执行以下操作:
$ join -t '<tab>' animals.txt colors.txt > output1
$ cut -f 3 output1 > output2
其中<tab>
是实际的制表符。 根据您的外壳,您可能可以使用ctrl-V和一个Tab键输入它。 (或使用其他分隔符进行剪切。)
我会用熊猫
animals, colors = read_table('animals.txt', index_col=0), read_table('colors.txt', index_col=0)
df = animals.join(colors)
结果是:
animals.join(colors)
Out[73]:
animal color
id
12345 dog black
23456 sheep white
34567 pig pink
然后按照ID的顺序将颜色输出到文件:
df.color.to_csv(r'out.csv', index=False)
如果您无法将列标题添加到文本文件中,则可以在导入时添加它们
animals = read_table('animals.txt', index_col=0, names=['id','animal'])
假设输入文件中的每一行的结构均与示例完全相同:
with open("c:\\python27\\output1.txt","w") as out1, \
open("c:\\python27\\output2.txt","w") as out2:
for outline in [animal[0]+"\t"+animal[1]+"\t"+color[1] \
for animal in [line.strip('\n').split("\t") \
for line in open("c:\\python27\\animals.txt","r").readlines()] \
for color in [line.strip('\n').split("\t") \
for line in open("c:\\python27\\colors.txt","r").readlines()] \
if animal[0] == color[0]]:
out1.write(outline+'\n')
out2.write(outline[outline.rfind('\t')+1:]+'\n')
我认为这将为您做到。
也许不是最优雅/快速/清晰的方法-但很短。 我认为从技术上讲这是4行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.