pandas 熊猫将行从 1 个 DF 移动到另一个 DF

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36142959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:54:55  来源:igfitidea点击:

Pandas move rows from 1 DF to another DF

pythonpandas

提问by yren

I have df1read from Excel, then I create an empty df2with the same columns. Now I want to move some rows from df1matching 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.

我已经df1从 Excel 中读取,然后我创建了一个df2具有相同列的空。现在我想将一些行从df1匹配某些条件移动到df2. 是否有任何简单的方法可以做到这一点,例如pop()在 中list,这意味着可以将项目弹出到新列表并从旧列表中删除。

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:

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

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

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

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

回答by Alexander

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