【问题标题】:Can someone explain the intuition of loops when used on dataframes?有人可以解释在数据帧上使用循环的直觉吗?
【发布时间】:2019-08-26 06:34:57
【问题描述】:

我想完全理解每一行代码的作用,因为我目前还不能 100% 确定。代码来自我正在 PythonProgramming.net 上观看的教程系列。

我相信第一个“If”语句是向 act_min_wage 数据框添加列,然后重命名它们?

“else”语句似乎将索引加入到新数据帧 act_min_wage?这是怎么回事?

为什么我们需要第一个 if 语句?第二个加入他们就够了吗?

非常感谢您的帮助。

act_min_wage = pd.DataFrame()

for name, group in df.groupby("State"):
    if act_min_wage.empty:
        act_min_wage = group.set_index("Year")[["Low.2018"]].rename(columns={"Low.2018":name})
    else:
        act_min_wage = act_min_wage.join(group.set_index("Year")[["Low.2018"]].rename(columns={"Low.2018":name}))

act_min_wage.head()

【问题讨论】:

    标签: python pandas loops logic


    【解决方案1】:

    1)act_min_wage = pd.DataFrame()

    创建空的DataFrame

    2) for name, group in df.groupby("State"):

    df.groupby("State") - 按列 "State" 对数据帧进行分组,因此在循环中 name - “状态”列的唯一值 group - df 中列 "State" 的值等于当前 name

    的所有行

    3)

     if act_min_wage.empty:
            act_min_wage = group.set_index("Year")[["Low.2018"]].rename(columns={"Low.2018":name})
    

    如果新的数据框 act_min_wage 为空(仅在第一次迭代时)放在那里 group 并将列 "Low.2018" 重命名为 namedf"State" 列的唯一值)

    4)

        else:
            act_min_wage = act_min_wage.join(group.set_index("Year")[["Low.2018"]].rename(columns={"Low.2018":name}))
    

    由于act_min_wage 不为空,根据Year 值加入新的group,默认为左加入。

    所以 if 语句用于将空数据框替换为 group 索引为 "Year"

    【讨论】:

    • 感谢您如此全面的解释,它确实为我澄清了这一点。
    【解决方案2】:

    通过玩具示例尝试此代码,以更好地理解所有步骤:

    import pandas as pd
    from IPython.display import display, HTML
    
    df = pd.DataFrame({'State': ['NY', 'NY', 'C', 'C', 'W'], 
                       'Low.2018': [0, 5, 10, 2, 3], 
                       'Year': [2017, 2018, 2017, 2018, 2017]})
    
    act_min_wage = pd.DataFrame()
    
    for name, group in df.groupby("State"):
        print('NEW ITERATION', '\n', 'Group:', '\n', '\t', name)
        display(group)
        print('\n', 'Current state of act_min_wage')
        display(act_min_wage)
        print('\n\n')
        if act_min_wage.empty:
            act_min_wage = group.set_index("Year")[["Low.2018"]].rename(columns={"Low.2018":name})
        else:
            act_min_wage = act_min_wage.join(group.set_index("Year")[["Low.2018"]].rename(columns={"Low.2018":name}))
    
    print('\n', 'Final state of act_min_wage')
    display(act_min_wage)
    

    【讨论】:

      猜你喜欢
      • 2020-08-16
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-04
      • 2018-03-09
      • 1970-01-01
      • 2019-07-11
      相关资源
      最近更新 更多