我有两个包含名称的数据集。什么是简单的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

最佳答案

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

关于python - 用其他数据框的两列对数据框进行子设置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52889084/

10-12 22:51
查看更多