在 Python Pandas DataFrame 中插入行

2022-01-09 00:00:00 python pandas dataframe row insert

问题描述

(我是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

相关文章