我有两个包含名称的数据集。什么是df2子集的简单易变的pythonish方式,因此它仅包含df1所包含的行(名字,姓氏)。谢谢。
import pandas as pd
names1 = {
'index' : [1, 2, 3],
'col1' : ['John', 'Jerry', 'John'],
'col2' : ['Doe', 'Peters', 'Smith']
}
names2 = {
'index' : [1, 2, 3, 4],
'col1' : ['John', 'Bob','Jerry', 'John'],
'col2' : ['Smith', 'Lacko', 'Peters', 'Nowak'],
'col3' : [12, 13, 14, 15]
}
df1 = pd.DataFrame(names1).set_index(["index"])
df2 = pd.DataFrame(names2).set_index(["index"])
print(df1,'\n')
print(df2)
col1 col2
index
1 John Doe
2 Jerry Peters
3 John Smith
col1 col2 col3
index
1 John Smith 12
2 Bob Lacko 13
3 Jerry Peters 14
4 John Nowak 15
所需的输出:
col1 col2 col3
index
1 John Smith 12
3 Jerry Peters 14
答案 0 :(得分:3)
在reset_index
之前使用merge
,然后在set_index
之前使用:
df = df2.reset_index().merge(df1).set_index('index')
print (df)
col1 col2 col3
index
1 John Smith 12
3 Jerry Peters 14
因为仅merge
丢失了原始索引值:
print (df2.merge(df1))
col1 col2 col3
0 John Smith 12
1 Jerry Peters 14