【问题标题】:Pandas: how to duplicate a row n times and insert at desired location of a dataframe?Pandas:如何复制一行 n 次并在数据框的所需位置插入?
【发布时间】: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])

这似乎是一种非常迟钝的方法来做一些我认为应该很简单的事情。我应该如何更轻松地完成这项工作?

【问题讨论】:

标签: python pandas


【解决方案1】:

这可以工作。将索引重置为一列,以便您可以在最后使用它进行排序。取出您想要的行并使用 np.reapeat 将其连接到原始 df 然后对索引 col 进行排序,删除它并重置索引。

import pandas as pd
import numpy as np

df = pd.DataFrame({'index': [0, 1, 2],
 'col 1': ['a01', 'a11', 'a21'],
 'col2': ['a02', 'a12', 'a22']})


index_to_copy = 0
number_of_extra_copies = 2
pd.concat([df,
           pd.DataFrame(np.repeat(df.iloc[[index_to_copy]].values,
                                  number_of_extra_copies,
                                  axis=0),
                        columns=df.columns)]).sort_values(by='index').drop(columns='index').reset_index(drop=True)

输出

    col 1   col2
0   a01     a02
1   a01     a02
2   a01     a02
3   a11     a12
4   a21     a22

【讨论】:

    猜你喜欢
    • 2018-11-10
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 2011-11-16
    相关资源
    最近更新 更多