【问题标题】:Insert Row in Python Pandas DataFrame在 Python Pandas DataFrame 中插入行
【发布时间】:2015-12-18 22:21:39
【问题描述】:

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

我已经搜索了一种在 Python 中将 Row 插入 Pandas DataFrame 的方法,我发现了这个:

add one row in a pandas.DataFrame

我使用了 fred 在该主题的已接受答案中提供的代码,但该代码覆盖了我的行: 我的代码(在某些条件下为每一列插入一行值“-1”):

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

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

希望你能理解我的问题。 (如有英文错误,请见谅)

谢谢。

更新:

有人建议这样做:

Is it possible to insert a row at an arbitrary position in a dataframe using pandas?

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

 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)

还有其他想法吗?

【问题讨论】:

标签: python pandas insert row dataframe


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 2017-05-20
    • 2020-08-12
    • 2018-01-21
    • 1970-01-01
    • 2018-08-13
    相关资源
    最近更新 更多