擅长:python、mysql、java
<p>为什么不使用<code>pd.concat()</code>方法?<a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow noreferrer">(see doc)</a></p>
<p>根据您的工作流程,可以在要插入新行的索引处对数据帧进行切片,然后按以下方式插入行:</p>
<pre><code>>>> d = {'col1': ['A', 'B', 'D'], 'col2': [1, 2, 4]}
>>> df = pd.DataFrame(data=d)
>>> df
col1 col2
0 A 1
1 B 2
2 D 4
>>> row = {'col1':['C'], 'col2': [3]}
>>> row = pd.DataFrame(data=row)
>>> new_df = pd.concat([df.iloc[:2], row, df.iloc[2:]]).reset_index(drop=True)
>>> new_df
col1 col2
0 A 1
1 B 2
2 C 3
3 D 4
</code></pre>
<p><code>Note</code>您需要在链式方法<code>reset_index()</code>中添加参数<code>drop=True</code>,否则您的“旧”索引将作为新列添加。在</p>
<p>希望这有帮助。在</p>