Python 通过来自其他数据帧的两列对数据帧进行子集设置
我有两个包含名称的数据集。EAIST pythonish以什么方式将df2子集化,使其只包含df1包含的行(名)。多谢各位Python 通过来自其他数据帧的两列对数据帧进行子集设置,python,pandas,dataframe,Python,Pandas,Dataframe,我有两个包含名称的数据集。EAIST pythonish以什么方式将df2子集化,使其只包含df1包含的行(名)。多谢各位 import pandas as pd names1 = { 'index' : [1, 2, 3], 'col1' : ['John', 'Jerry', 'John'], 'col2' : ['Doe', 'Peters', 'Smith'] } names2 = { 'index' : [1, 2, 3, 4],
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
使用之前和之后:
因为只有merge
丢失了原始索引值:
print (df2.merge(df1))
col1 col2 col3
0 John Smith 12
1 Jerry Peters 14
print (df2.merge(df1))
col1 col2 col3
0 John Smith 12
1 Jerry Peters 14