使用熊猫:import pandas as pd
id1 = pd.read_csv('id1.txt')
id2 = pd.read_csv('id2.txt')
df = id1.merge(id2.sort_values(by='ID2').drop_duplicates('ID2').rename(columns={'ID2':'ID1'}))
print(df)
产生:
^{pr2}$
对于大型数据集,您可能需要执行以下操作:# [Optional] sort locations and drop duplicates
id2.sort_values(by='ID2', inplace=True)
id2.drop_duplicates('ID2', inplace=True)
# columns that you are merging must have the same name
id2.rename(columns={'ID2':'ID1'}, inplace=True)
# perform the merge
df = id1.merge(id2)
如果没有drop-duplicates,则每个项目都有一行:df = id1.merge(id2.rename(columns={'ID2':'ID1'}))
print(id2)
print(df)
给予:ID2 RA DEC
0 101 4.5 10.5
1 107 90.1 55.5
2 102 30.5 3.3
3 103 60.1 40.6
4 104 10.8 5.6
5 103 60.1 40.6
6 104 10.9 5.6
ID1 z e PA n RA DEC
0 101 1.0 1.2 1.5 1.8 4.5 10.5
1 104 1.5 1.8 2.2 3.1 10.8 5.6
2 104 1.5 1.8 2.2 3.1 10.9 5.6
请注意,此解决方案保留了列的不同类型:>>> id1.ID1.dtype
dtype('int64')
>>> id1[' z'].dtype
dtype('float64')
由于在标题行中逗号后面有空格,因此这些空格成为列名的一部分,因此需要使用id1['z']引用第二列。通过修改read语句,不再需要执行以下操作:>>> id1 = pd.read_csv('id1.txt', skipinitialspace=True)
>>> id1.z.dtype
dtype('float64')