在pandas数据框中插入一行 [英] Insert a row to pandas dataframe

查看:112
本文介绍了在pandas数据框中插入一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框:

s1 = pd.Series([5, 6, 7])
s2 = pd.Series([7, 8, 9])

df = pd.DataFrame([list(s1), list(s2)],  columns =  ["A", "B", "C"])

   A  B  C
0  5  6  7
1  7  8  9

[2 rows x 3 columns]

我需要添加第一行[2、3、4]以获得:

and I need to add a first row [2, 3, 4] to get:

   A  B  C
0  2  3  4
1  5  6  7
2  7  8  9

我已经尝试过append()concat()函数,但是找不到正确的方法.

I've tried append() and concat() functions but can't find the right way how to do that.

如何在数据框中添加/插入系列?

How to add/insert series to dataframe?

推荐答案

只需使用loc将行分配给特定索引:

Just assign row to a particular index, using loc:

 df.loc[-1] = [2, 3, 4]  # adding a row
 df.index = df.index + 1  # shifting index
 df = df.sort_index()  # sorting by index

然后您会得到所需的:

    A  B  C
 0  2  3  4
 1  5  6  7
 2  7  8  9

请参见熊猫文档索引:设置为放大.

这篇关于在pandas数据框中插入一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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