python - 将给定行移动到 DataFrame 的末尾

标签 python pandas dataframe concatenation

我想从 DataFrame 中取出给定的行并添加到相同的 DataFrame 中。

我下面的代码就是这样做的,但我不确定我这样做的方式是否正确,或者是否有更简单、更好、更快的方式?

testdf = df.copy()
#get row 
target_row = testdf.ix[[2],:]
#del row from df
testdf.drop([testdf.index[2]], axis=0, inplace=True)
#concat original row to end or start of df
newdf = pd.concat([testdf, target_row], axis=0)

谢谢

最佳答案

而不是 concat 我会在 shift 之后直接分配给 df ing,然后使用 iloc 来引用您要分配行的位置,您必须调用 squeeze 以便您只分配值并丢失原始索引值,否则它将引发一个 ValueError:

In [210]:
df = pd.DataFrame({'a':np.arange(5)})
df

Out[210]:
   a
0  0
1  1
2  2
3  3
4  4

In [206]:
target_row = df.ix[[2],:]
target_row

Out[206]:
   a
2  2

In [211]:
df = df.shift()
df.iloc[0] = target_row.squeeze()
df

Out[211]:
   a
0  2
1  0
2  1
3  2
4  3

编辑

在最后插入:

In [255]:
df = pd.DataFrame({'a':np.arange(5)})
target_row = df.ix[[2],:]
df = df.shift(-1)
df.iloc[-1] = target_row.squeeze()
df

Out[255]:
   a
0  1
1  2
2  3
3  4
4  2

另一个更新

感谢@AsheKetchum 指出我之前的回答是错误的,现在 3 年后看这个我意识到你可以reindex orig df:

如果我们将索引的副本作为列表:

In[24]:
idx = df.index.tolist()
idx

Out[24]: [0, 1, 2, 3, 4]

然后我们可以从这个列表中弹出感兴趣的索引:

In[25]:
idx.pop(2)
idx

Out[25]: [0, 1, 3, 4]

现在我们可以重新索引通过添加到这个列表中:

In[26]:
df.reindex([2] + idx)

Out[26]: 
   a
2  2
0  0
1  1
3  3
4  4

或追加:

In[27]:    
df.reindex(idx+[2])

Out[27]: 
   a
0  0
1  1
3  3
4  4
2  2

关于python - 将给定行移动到 DataFrame 的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30940773/

相关文章:

python - 使用waf,如何在配置期间检查python模块的最低版本?

python - 根据来自多个行索引的多个列的值的聚合创建一个列

python - Pandas 可以按行执行 min() 和 max() 函数吗?

r - 如何根据R中的相似值合并两个数据帧

python - 优化将值转换为 0 和 1 的性能

Python 时间 : How to initialize arguments for timed function before every repetition?

python - virtualenv 到 Windows 10 上的路径

python - 如何从 Datareader pandas 中挑选出单独的数值列?

python - 如何使用 Opencv 和 Flask 将网络摄像头图像流广播到多个设备?

Python - 更好的循环解决方案 - 出现错误后重新运行并在 3 次尝试后忽略该错误