pandas 将行从 1 个 DF 移动到另一个 DF [英] Pandas move rows from 1 DF to another DF

查看:85
本文介绍了 pandas 将行从 1 个 DF 移动到另一个 DF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 Excel 中读取了 df1,然后我创建了一个具有相同列的空 df2.现在我想将一些行从 df1 匹配一些条件移动到 df2.有没有什么简单的方法可以像 list 中的 pop() 那样做到这一点,这意味着可以将项目弹出到新列表并从旧列表中删除.

I have df1 read from Excel, then I create an empty df2 with the same columns. Now I want to move some rows from df1 matching some condition to df2. Is there any easy way to do this like pop() in list, meaning the item can be popped to new list and deleted from the old list.

我正在做的是将这些行附加到 df2,然后 df1=df1[~condition] 将它们从 df1 中删除,但是我总是收到烦人的警告:

What I am doing is append these rows to df2, then df1=df1[~condition] to remove them from df1, but I always got annoying warnings:

"UserWarning: Boolean Series key will be reindexed to match DataFrame index.
"DataFrame index.", UserWarning)"

我认为上面的警告是由于"df1=df1[~condition]",评论后警告消失了.

I think above warning is due to "df1=df1[~condition]", after comment this the warning disappeared.

推荐答案

如果您不关心索引(看起来您并不关心),那么您可以执行以下操作:

If you do not care about your index (which it appears you do not), then you can do the following:

np.random.seed(0)
df1 = pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
df2 = pd.DataFrame(columns=df1.columns)

>>> df1
          A         B         C
0  1.764052  0.400157  0.978738
1  2.240893  1.867558 -0.977278
2  0.950088 -0.151357 -0.103219
3  0.410599  0.144044  1.454274
4  0.761038  0.121675  0.443863

cond = df1.A < 1
rows = df1.loc[cond, :]
df2 = df2.append(rows, ignore_index=True)
df1.drop(rows.index, inplace=True)

>>> df1
          A         B         C
0  1.764052  0.400157  0.978738
1  2.240893  1.867558 -0.977278

>>> df2
          A         B         C
0  0.950088 -0.151357 -0.103219
1  0.410599  0.144044  1.454274
2  0.761038  0.121675  0.443863

这篇关于 pandas 将行从 1 个 DF 移动到另一个 DF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆