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

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

问题描述

(我是python新手,如有错误请见谅,希望你能理解我)

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

我已经搜索了一种在 Python 中将 Row 插入 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 行额外的新行).

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)

谢谢.

更新:

有人建议这样做:

是否可以使用 pandas 在数据框中的任意位置插入一行?

试过了,没用.事实上,它什么也不做,不添加任何行.

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的位置:p>

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天全站免登陆