Insert Row in Python Pandas DataFrame(在 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 中插入行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python Pandas DataFrame 中插入行
基础教程推荐
- 包装空间模型 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
