【问题标题】:Duplicate rows based on value with condition [duplicate]基于具有条件的值复制行[重复]
【发布时间】:2020-05-16 16:58:02
【问题描述】:

我需要像这样复制熊猫数据框中的一些行

name  times
   A      2
   B      1
   C      3
   D     20
...

我需要的是在 col2 值小于 20 时复制行

我现在做的是:

for t in df["times"]:
       if t < 20:
           df = df.loc[df.index.repeat(t)]

但是脚本一直在运行,我必须停止它(我已经等了很长时间了......)。

有什么方法可以改进或以其他方式做到这一点?

【问题讨论】:

  • @Viskovitz 我在理解您的需求时遇到了一些问题。我们是否很好地假设您想要重复行与“次”中的值一样多次?例如。重复“C”三次,而不是两次?
  • 我需要获得与 times 列的初始值一样多的相同行。如果“C”在时间列中有 3,则最终数据帧必须具有“C”树时间。

标签: python pandas dataframe duplicates


【解决方案1】:

用途:

#condition lt for <
mask = df['times'].lt(20)
#filter by boolean indexing
df1 = df[mask].copy()
#repeat rows
df1 = df1.loc[df1.index.repeat(df1['times'])]

#add rows higher like 20, sorting and create default index
df = pd.concat([df1, df[~mask]]).sort_index().reset_index(drop=True)
print (df)
  name  times
0    A      2
1    A      2
2    B      1
3    C      3
4    C      3
5    C      3
6    D     20

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    • 2018-05-08
    相关资源
    最近更新 更多