Pandas将行从一个数据框移动到另一个数据框

10
我已经从Excel中读取了df1,然后创建了一个与它具有相同列的空df2。现在我想将一些符合条件的df1行移动到df2中。是否有类似于list中的pop()的简单方法,意思是可以将项目弹出到新列表中并从旧列表中删除?
我的做法是将这些行附加到df2,然后使用df1 = df1 [~condition]将它们从df1中移除,但我总是得到令人烦恼的警告:
"UserWarning: Boolean Series key will be reindexed to match DataFrame index.
"DataFrame index.", UserWarning)"

我认为上面的警告是由于"df1=df1[~condition]"引起的,注释掉后警告消失了。


你可能想看一下这个链接:https://dev59.com/g2_Xa4cB1Zd3GeqP021p - Stryker
2
嗨,你建议的链接是针对 R 而不是 Python。 - yren
1个回答

30

如果你不关心你的索引(似乎确实如此),那么你可以按照以下方式操作:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接