XUT*_*ADO 4 python subset pandas
我的数据帧df是3020x4。我想从原始图片中删除df1 20x4子集。换句话说,我只想得到形状为3000x4的差异。我尝试了下面的方法,但是没有用。它恰好返回了df。你能帮忙吗?谢谢。
new_df = df.drop(df1)
Run Code Online (Sandbox Code Playgroud)
如您似乎无法发布一个具有代表性的示例,我将演示一种使用mergeparam的方法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
Run Code Online (Sandbox Code Playgroud)
取一个子集:
In [118]:
df_subset=df.iloc[2:3]
df_subset
Out[118]:
a b c
2 0.53456 -0.781352 1.978084
Run Code Online (Sandbox Code Playgroud)
现在执行一个左merge与PARAM indicator=True这将增加_merge,其指示该行是否是列left_only,both或right_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
Run Code Online (Sandbox Code Playgroud)
这是原始合并的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
Run Code Online (Sandbox Code Playgroud)
的熊猫速查表还提出了以下技术
adf[~adf.x1.isin(bdf.x1)]
Run Code Online (Sandbox Code Playgroud)
其中 x1 是要比较的列,adf 是从中取出出现在数据帧 bdf 中的相应行的数据帧。
OP提出的特定问题也可以通过以下方式解决
new_df = df.drop(df1.index)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4570 次 |
| 最近记录: |