【问题标题】:Add a row when a conditions match?条件匹配时添加一行?
【发布时间】:2019-04-06 09:17:48
【问题描述】:

我想在条件匹配时添加一行并在所有列中填充值。下面的代码运行良好,但由于数据帧非常庞大,因此需要花费大量时间。这可以优化吗?

for i in range(len(df)):
    if df['counter'][i]==1:
        df.loc[len(df)]=[df['user_id'][i],df['start_time'][i]-datetime.timedelta(seconds=1),'psuedo_App_start',np.nan,0,np.nan,0]

【问题讨论】:

  • 是否可以添加一些示例数据,5 行?
  • 还有多个if df['counter'][i]==1: 比如if df['counter'][i]==2:, if df['counter'][i]==3: ?

标签: python pandas


【解决方案1】:

您可以使用DataFrame.assign 将过滤行更改为dictionary,然后将concat 更改为原始行,DataFrame.sort_index 最后使用DataFrame.reset_index 作为默认唯一索引:

d = {'event_name':'psuedo_App_start',
     'event_desc': np.nan,
     'Notification_process':0,
     'current_screen':np.nan,
     'counter': 0}

df1 = df[df['counter'] == 1].assign(**d).copy()

#if necessary subtract one second
#df1['start_time'] -= datetime.timedelta(seconds=1)
df = pd.concat([df1, df]).sort_index().reset_index(drop=True)

【讨论】:

    猜你喜欢
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    相关资源
    最近更新 更多