代码之家  ›  专栏  ›  技术社区  ›  Jasper

PANDA:函数中的列值分配不起作用

  •  0
  • Jasper  · 技术社区  · 7 年前

    我有一个这样的数据集:

    country | year      | supporting_nation | eco_sup  | mil_sup
    ------------------------------------------------------------------
      Fake       1984        US                 1          1
      Fake       1984        SU                 0          1
    

    在这个假例子中,一个国家在冷战期间扮演着两面派的角色,并得到了双方的支持。

    我正在以两种方式重塑数据集:

    1. 我删除了所有非美苏支持实例,我只对这两个国家感兴趣
    2. 我想把它减到 1 line per year per country ,这意味着我要为每个变量添加特定于us/su的伪变量。

    就像这样:

    country |   year      | US_SUP | US_eco_sup  | US_mil_sup | SU_SUP | SU_eco_sup  | SU_mil_sup |
        ------------------------------------------------------------------------------------------
     Fake       1984        1             1          1         1          1             1
     Fake       1985        1             1          1         1          1             1
     florp      1984        0             0          0         1          1             1
     florp      1985        0             0          0         1          1             1
    

    我添加了所有的假人和 US_SUP SU_SUP 已用正确的值填充了列。

    但是,我在为其他变量提供正确的值时遇到了困难。

    为此,我编写了以下函数:

    def get_values(x):
        cols = ['eco_sup', 'mil_sup']
        nation = ''
        if x['SU_SUP'] == 1:
            nation = 'SU_'
        if x['US_SUP'] == 1:
            nation = 'US_'
    
        support_vars = x[['eco_sup', 'mil_sup']]
        # Since each line contains only one measure of support I can
        # automatically assume that the support_vars are from
        # the correct nation
        support_cols = [nation + x for x in cols]
        x[support_cols] = support_vars
    

    这个计划比使用 df.groupby.agg('max') 操作,但作为上面返回的函数,我从未到达此步骤 0 对于每个新的虚拟列,不考虑数据帧中列的值。

    所以在最后一张桌子上 US/SU_mil/eco_sup 变量将为0。

    有人知道我做错了什么/为什么列得到了错误的值吗?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Jasper    7 年前

    我通过放弃 .apply 函数并使用它(其中 old 是旧变量名的列表)

    for index, row in df.iterrows():
        if row['SU_SUP'] == 1:
            nation = 'SU_'
            for col in old:
                df[index: index + 1][nation + col] = int(row[col])
        if row['US_SUP'] == 1:
            nation = 'US_'
            for col in old:
                df[index: index + 1][nation + col] = int(row[col])
    

    这就成功了!