gpt4 book ai didi

python - 如何在 Python 中删除数据框的子集?

转载 作者:太空狗 更新时间:2023-10-30 02:09:02 25 4
gpt4 key购买 nike

我的数据框 df 是 3020x4。我想从原始文件中删除子集 df1 20x4。换句话说,我只想得到形状为 3000x4 的差异。我尝试了以下但没有用。它准确地返回了 df。你能帮忙吗?谢谢。

new_df = df.drop(df1)

最佳答案

由于您似乎无法发布具有代表性的示例,我将演示一种使用 merge 和参数 indicator=True 的方法:

因此生成一些数据:

In [116]:
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
df

Out[116]:
a b c
0 -0.134933 -0.664799 -1.611790
1 1.457741 0.652709 -1.154430
2 0.534560 -0.781352 1.978084
3 0.844243 -0.234208 -2.415347
4 -0.118761 -0.287092 1.179237

取一个子集:

In [118]:
df_subset=df.iloc[2:3]
df_subset

Out[118]:
a b c
2 0.53456 -0.781352 1.978084

现在使用参数 indicator=True 执行左 merge 这将添加 _merge 列,指示该行是否为 left_onlybothright_only(后者不会出现在本例中),我们过滤合并的 df 以仅显示 left_only:

In [121]:
df_new = df.merge(df_subset, how='left', indicator=True)
df_new = df_new[df_new['_merge'] == 'left_only']
df_new

Out[121]:
a b c _merge
0 -0.134933 -0.664799 -1.611790 left_only
1 1.457741 0.652709 -1.154430 left_only
3 0.844243 -0.234208 -2.415347 left_only
4 -0.118761 -0.287092 1.179237 left_only

这是原始的合并 df:

In [122]:
df.merge(df_subset, how='left', indicator=True)

Out[122]:
a b c _merge
0 -0.134933 -0.664799 -1.611790 left_only
1 1.457741 0.652709 -1.154430 left_only
2 0.534560 -0.781352 1.978084 both
3 0.844243 -0.234208 -2.415347 left_only
4 -0.118761 -0.287092 1.179237 left_only

关于python - 如何在 Python 中删除数据框的子集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39408109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com