在Python Pandas DataFrame中插入行 [英] Insert Row in Python Pandas DataFrame

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

问题描述

(我是python的新手,对我犯的任何错误深表歉意,希望你能理解我)

(I´m new to python, sorry for any mistakes I make, I hope you can understand me)

我搜索了一种在Python中将行插入到Pandas DataFrame中的方法,并且发现了这一点:

I have searched for a method to insert a Row into a Pandas DataFrame in Python, and I have found this:

在pandas.DataFrame中添加一行

我已经使用了fred在该主题的可接受答案中提供的代码,但是该代码覆盖了我的行: 我的代码(在某些情况下,为每列插入一个值为"-1"的行):

I have use the code provided in the accepted answer of that topic by fred, but the code overwrites my row: My code (Inserts a row with values "-1" for each column in certains conditions):

df.loc[i+1] = [-1 for n in range(len(df.columns))]

如何使代码插入一行而不覆盖它? 例如,如果我有一个50行的DataFrame,则在位置25插入一行(仅作为示例),并使DataFrame具有51行(将25行作为一个额外的NEW行).

How can I make the code insert a row WITHOUT overriding it? For example, if I have a 50 row DataFrame, insert a row in position 25 (Just as an example), and make the DataFrame have 51 rows (Being the 25 a extra NEW row).

希望您能理解我的问题. (对于任何英语错误,深表歉意)

I hope you can understand my question. (Sorry for any english mistakes)

谢谢.

更新:

有人建议这样做:

尝试过,没有用.实际上,它什么也不做,不添加任何行.

Tried, did not work. In fact, it does nothing, does not add any row.

 line = pd.DataFrame({[-1 for n in range(len(df.columns))]}, index=[i+1])
 df = pd.concat([ df.ix[:i],  line,  df.ix[i+1:]]).reset_index(drop=True)

还有其他想法吗?

推荐答案

使用小DataFrame,如果要插入行,则在位置1:

With a small DataFrame, if you want to insert a line, at position 1:

df = pd.DataFrame({'a':[0,1],'b':[2,3]})

df1 = pd.DataFrame([4,5]).T  

pd.concat([df[:1], df1.rename(columns=dict(zip(df1.columns,df.columns))), df[1:]])

#Out[46]: 
#   a  b
#0  0  2
#0  4  5
#1  1  3

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

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