【发布时间】:2021-03-29 01:29:09
【问题描述】:
假设我有一个如下的数据框:
| index | col 1 | col2 |
|---|---|---|
| 0 | a01 | a02 |
| 1 | a11 | a12 |
| 2 | a21 | a22 |
我想将一行复制 n 次,然后在某个索引处插入复制的行。例如将第 0 行复制 2 次,然后在原始第 0 行之前插入:
| index | col 1 | col2 |
|---|---|---|
| 0 | a01 | a02 |
| 1 | a01 | a02 |
| 2 | a01 | a02 |
| 3 | a11 | a12 |
| 4 | a21 | a22 |
我现在正在做的是创建一个空数据框,然后用我想要复制的行的值填充它。
# create empty dataframe with 2 rows
temp_df = pd.DataFrame(columns=original_df.columns, index=list(range(2)))
# replacing each column by target value, I don't know how to do this more efficiently
temp_df.iloc[:,0] = original_df.iloc[0,0]
temp_df.iloc[:,1] = original_df.iloc[0,1]
temp_df.iloc[:,2] = original_df.iloc[0,2]
# concat the dataframes together
# to insert at indexes in the middle, I would have to slice the original_df and concat separately
original_df = pd.concat([temp_df, original_df])
这似乎是一种非常迟钝的方法来做一些我认为应该很简单的事情。我应该如何更轻松地完成这项工作?
【问题讨论】: