Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过来自其他数据帧的两列对数据帧进行子集设置_Python_Pandas_Dataframe - Fatal编程技术网

Python 通过来自其他数据帧的两列对数据帧进行子集设置

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],

我有两个包含名称的数据集。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], 
    '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