[英]Pandas move rows from 1 DF to another DF
I have df1
read from Excel, then I create an empty df2
with the same columns. 我从Excel中读取df1
,然后创建一个具有相同列的空df2
。 Now I want to move some rows from df1
matching some condition to df2
. 现在我想从df1
移动一些匹配某些条件的行到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. 是否有任何简单的方法来执行此操作,如list
pop()
,这意味着该项可以弹出到新列表并从旧列表中删除。
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]"
,在评论之后警告消失了。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.