【发布时间】:2018-05-04 14:24:57
【问题描述】:
让我们假设一个 df1
df1 = pd.DataFrame(
{'col1': {0: 500.0, 1: 500.0, 2: 833.3, 3: 500.0, 4: 833.3, 5: 500.0, 6: 833.3},
'col2': {0: 1833.3, 1: 1000.0, 2: 1833.3, 3: 2666.7, 4: 1833.3, 5: 3500.0, 6: 1000.0},
'col3': {0: 250.0, 1: 250.0, 2: 30.0, 3: 30.0, 4: 30.0, 5: 103.3, 6: 176.7},
'col4': {0: 3.4, 1: 4.0, 2: 2.2, 3: 3.4, 4: 2.2, 5: 4.0, 6: 3.4},
'col5': {0: 0.25, 1: 0.15, 2: 0.1, 3: 0.25, 4: 0.25, 5: 0.1, 6: 0.1},
'col6': {0: 364, 1: 937, 2: 579, 3: 313, 4: 600, 5: 49, 6: 13}})
还有一个 df2
df2 = pd.DataFrame(
{'col1': {0: 833.3, 1: 500.0, 2: 500.0, 3: 500.0, 4: 500.0, 5: 500.0, 6: 500.0, 7: 833.3, 8: 500.0, 9: 833.3, 10: 500.0, 11: 500.0, 12: 833.3, 13: 833.3, 14: 833.3},
'col2': {0: 1833.3, 1: 1000.0, 2: 1833.3, 3: 3500.0, 4: 3500.0, 5: 1000.0, 6: 2666.7, 7: 1833.3, 8: 2666.7, 9: 1000.0, 10: 2666.7, 11: 2666.7, 12: 1000.0, 13: 1833.3, 14: 1833.3},
'col3': {0: 30.0, 1: 250.0, 2: 250.0, 3: 103.3, 4: 176.7, 5: 103.3, 6: 30.0, 7: 103.3, 8: 30.0, 9: 176.7, 10: 250.0, 11: 103.3, 12: 30.0, 13: 30.0, 14: 250.0},
'col4': {0: 2.2, 1: 4.0, 2: 3.4, 3: 4.0, 4: 2.2, 5: 2.8, 6: 2.8, 7: 2.8, 8: 3.4, 9: 3.4, 10: 2.8, 11: 2.8, 12: 3.4, 13: 2.2, 14: 2.8},
'col5': {0: 0.25, 1: 0.15, 2: 0.25, 3: 0.1, 4: 0.2, 5: 0.15, 6: 0.15, 7: 0.25, 8: 0.25, 9: 0.1, 10: 0.15, 11: 0.1, 12: 0.15, 13: 0.1, 14: 0.2}})
在 df2 中删除 col1 和 col2 以及 col3 和 col4(以及 coln )与 df1 的相应列具有相同值的行的最 Pythonic 方法是什么? 我不想合并数据框,只删除 df2 中的任何行(可能是多个),其中兴趣列上的行元组在两个 dfs 中是相同的。
我只是想出了如何使用:
new_df = df2.loc[df2[col1].isin(df1[col1]) &
df2[col2].isin(df1[col2]) &
df2[col3].isin(df1[col3]) &
df2[col4].isin(df1[col4]) &
df2[col5].isin(df1[col5]) ]
这对于更大的数据集和更多的列来说有点麻烦。
有什么更好的方法吗?
【问题讨论】:
-
我试图要求澄清。目前我认为我还没有找到正确的答案。
-
我现在明白了。主要问题是我们无法重现您的错误。描述很好,但是如果您能够edit 提出问题并举例说明问题(无论是温的还是我的,谁的都无所谓),那么真正 会有什么帮助。我已经用你的数据测试了我的解决方案,它似乎有效。
-
我尝试将数据制作成易于复制的格式。希望这有助于找到更好的解决方案
标签: python python-3.x pandas dataframe