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

查看:38
本文介绍了向 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 文档 Indexing: Setting with放大.

See in Pandas documentation Indexing: Setting with enlargement.

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

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