【问题标题】:Iterating a dataframe and updating (adding on to the existing) instead of it being replaced迭代数据框并更新(添加到现有的)而不是被替换
【发布时间】:2022-01-13 23:52:13
【问题描述】:

我有一个空数据框,当它通过循环时,返回与列表中最后一个值的条件匹配的结果,而不是考虑所有的值。

数据框被替换为列表中的每个条件,而不是被添加到其中。

我试过empty_df.append(...),还是不行。

njobs = ['doc', 'phy', 'sci', 'math', 'stat']
empty_df = pd.DataFrame() 

for i in njobs:
    df_new = df.loc[df['title'] == i]
    
    
    empty_df['skills'] = df_new[['(Level 6)','(Level 5)',
                                     '(Level 4)','(Level 3)', '(Level 2)',
                                     '(Level 1)',
                                     '(Level 0)']]
    
    empty_df['cat_id'] = df_new[['(L6)','(L5)','(L4)','(L3)',
                             '(L2)','(L1)', 'ID']]
    
    empty_df['wt'] = df_new[['Weight']]
    
    empty_df['job'] = i

【问题讨论】:

    标签: python pandas dataframe iteration


    【解决方案1】:

    您可以每次在 lopp 中创建一个新数据帧,最后可以使用 pd.concat([df_doc, df_phy,.. df_stat]) 连接它们

    【讨论】:

    • 我给了一个样本清单。我的列表中有 500 多个项目。
    • 你能提供更多细节吗?我不认为你会需要循环然后..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 2020-02-15
    • 2019-07-08
    • 2020-10-13
    • 1970-01-01
    • 2018-03-23
    相关资源
    最近更新 更多