简体   繁体   English

在Python Pandas DataFrame中插入行

[英]Insert Row in Python Pandas DataFrame

(I´m new to python, sorry for any mistakes I make, I hope you can understand me) (我是python的新手,对我犯的任何错误深表歉意,希望你能理解我)

I have searched for a method to insert a Row into a Pandas DataFrame in Python, and I have found this: 我搜索了一种在Python中将行插入到Pandas DataFrame中的方法,并且发现了这一点:

add one row in a pandas.DataFrame 在pandas.DataFrame中添加一行

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): 我已经使用了fred在该主题的可接受答案中提供的代码,但是该代码覆盖了我的行:我的代码(在某些情况下,每列插入值为“ -1”的行):

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

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). 例如,如果我有一个50行的DataFrame,则在位置25插入一行(仅作为示例),并使DataFrame具有51行(将25行作为一个额外的NEW行)。

I hope you can understand my question. 希望你能理解我的问题。 (Sorry for any english mistakes) (对于任何英语错误深表歉意)

Thank you. 谢谢。

UPDATE: 更新:

Someone suggested this: 有人建议这样做:

Is it possible to insert a row at an arbitrary position in a dataframe using 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)

Any other ideas? 还有其他想法吗?

With a small DataFrame , if you want to insert a line, at position 1 : 对于较小的DataFrame ,如果要在位置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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM