【问题标题】:For loop is not working while appending rows追加行时,for循环不起作用
【发布时间】:2021-11-29 14:25:06
【问题描述】:

我正在尝试遍历我的数据框,并为 df.con 中的每个元素寻找额外的 3 行,这仅在第二个元素US 上循环并且缺少 UK

请查找附件代码。

import pandas as pd
d = { 'year': [2019,2019,2019,2020,2020,2020], 
      'age group': ['(0-14)','(14-50)','(50+)','(0-14)','(14-50)','(50+)'], 
      'con': ['UK','UK','UK','US','US','US'],
      'population': [10,20,300,400,1000,2000]}
df = pd.DataFrame(data=d)
df2 = df.copy()
df

year    age group   con population
0   2019    (0-14)  UK  10
1   2019    (14-50) UK  20
2   2019    (50+)   UK  300
3   2020    (0-14)  US  400
4   2020    (14-50) US  1000
5   2020    (50+)   US  2000
n_df_2 = df.copy()
con_list = [x for x in df.con]
year_list = [x for x in df.year]
age_list = [x for x in df['age group']]
new_list = ['young vs child','old vs young', 'unemployed vs working']

for country in df.con:

      bev_child =  n_df_2[(n_df_2['con'].str.contains(country)) & (n_df_2['age group'].str.contains(age_list[0]))]
      bev_work =  n_df_2[(n_df_2['con'].str.contains(country)) & (n_df_2['age group'].str.contains(age_list[1]))]
      bev_old =  n_df_2[(n_df_2['con'].str.contains(country)) & (n_df_2['age group'].str.contains(age_list[2]))]


      bev_child.loc[:,'population'] = bev_work.loc[:,'population'].max() / bev_child.loc[:,'population'].max() 
      bev_child.loc[:,'con'] = country +'-'+new_list[0]
      bev_child.loc[:,'age group'] = new_list[0]
      s = n_df_2.append(bev_child, ignore_index=True)


      bev_child.loc[:,'population'] = bev_child.loc[:,'population'].max() + bev_old.loc[:,'population'].max()/ bev_work.loc[:,'population'].max() 
      bev_child.loc[:,'con'] = country +'-'+ new_list[2]
      bev_child.loc[:,'age group'] = new_list[2]

      s = s.append(bev_child, ignore_index=True)

      bev_child.loc[:,'population'] = bev_old.loc[:,'population'].max() / bev_work.loc[:,'population'].max() 
      bev_child.loc[:,'con'] = country +'-'+ new_list[1]
      bev_child.loc[:,'age group'] = new_list[1]

      s = s.append(bev_child, ignore_index=True)
s

输出缺少的英国行...


year    age group                   con                     population
0   2019    (0-14)                  UK                      10.0
1   2019    (14-50)                 UK                      20.0
2   2019    (50+)                   UK                      300.0
3   2020    (0-14)                  US                      400.0
4   2020    (14-50)                 US                      1000.0
5   2020    (50+)                   US                      2000.0
6   2020    young vs child          US-young vs child          2.5
7   2020    unemployed vs working   US-unemployed vs working   4.5
8   2020    old vs young             US-old vs young           2.0

【问题讨论】:

    标签: python pandas dataframe loops for-loop


    【解决方案1】:

    每次循环时,s 都会在这一行重新初始化为一个新的数据帧:

    s = n_df_2.append(bev_child, ignore_index=True)
    

    这使得s 最终成为n_df_2 的原始值,加上最后一次执行循环体时附加到它的三个值。

    我认为这更接近你想要的(在循环改变之前什么都没有):

    for country in df.con.unique():
    
        bev_child = n_df_2[(n_df_2['con'].str.contains(country)) & (n_df_2['age group'].str.contains(age_list[0]))]
        bev_work = n_df_2[(n_df_2['con'].str.contains(country)) & (n_df_2['age group'].str.contains(age_list[1]))]
        bev_old = n_df_2[(n_df_2['con'].str.contains(country)) & (n_df_2['age group'].str.contains(age_list[2]))]
    
        bev_child.loc[:, 'population'] = bev_work.loc[:, 'population'].max() / bev_child.loc[:, 'population'].max()
        bev_child.loc[:, 'con'] = country + '-' + new_list[0]
        bev_child.loc[:, 'age group'] = new_list[0]
        n_df_2 = n_df_2.append(bev_child, ignore_index=True)
    
        bev_child.loc[:, 'population'] = bev_child.loc[:, 'population'].max() + bev_old.loc[:,
                                                                                'population'].max() / bev_work.loc[:,
                                                                                                      'population'].max()
        bev_child.loc[:, 'con'] = country + '-' + new_list[2]
        bev_child.loc[:, 'age group'] = new_list[2]
        n_df_2 = n_df_2.append(bev_child, ignore_index=True)
    
        bev_child.loc[:, 'population'] = bev_old.loc[:, 'population'].max() / bev_work.loc[:, 'population'].max()
        bev_child.loc[:, 'con'] = country + '-' + new_list[1]
        bev_child.loc[:, 'age group'] = new_list[1]
        n_df_2 = n_df_2.append(bev_child, ignore_index=True)
    
    print(n_df_2)
    

    输出:

        year              age group                       con  population
    0   2019                 (0-14)                        UK        10.0
    1   2019                (14-50)                        UK        20.0
    2   2019                  (50+)                        UK       300.0
    3   2020                 (0-14)                        US       400.0
    4   2020                (14-50)                        US      1000.0
    5   2020                  (50+)                        US      2000.0
    6   2019         young vs child         UK-young vs child         2.0
    7   2019  unemployed vs working  UK-unemployed vs working        17.0
    8   2019           old vs young           UK-old vs young        15.0
    9   2020         young vs child         US-young vs child         2.5
    10  2020  unemployed vs working  US-unemployed vs working         4.5
    11  2020           old vs young           US-old vs young         2.0
    

    请注意,这只循环遍历df.con 中的唯一值,因此循环体只运行两次。每次循环运行时,都会将三个记录添加到输出中。另请注意,输出附加到n_df_2,因此不需要变量s

    【讨论】:

    • 谢谢兄弟。祝你星期天快乐 :) 我如何将我的 stackoverflow 问题发送给你。我可以加入你或联系你吗。。
    • stackoverflow.com/questions/69495398/…这个我也放了赏金..请检查
    猜你喜欢
    • 2013-08-08
    • 2017-10-12
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    相关资源
    最近更新 更多