【问题标题】:Loop through dataframe to change a columns values - python [duplicate]循环遍历数据框以更改列值-python [重复]
【发布时间】:2020-11-09 10:06:34
【问题描述】:

我有一个包含月份列的 df。月份是它们的数值,即从 1 到 12。我需要将它们读取为它们的实际文本等价物,以便将 1 替换为一月,将 2 替换为二月,依此类推。

目前我正在通过分别声明每个月来做这件事:

cntryPerMonth.loc[cntryPerMonth['Month'] == 1.0, 'Month'] = 'January'
cntryPerMonth.loc[cntryPerMonth['Month'] == 2.0, 'Month'] = 'February'
cntryPerMonth.loc[cntryPerMonth['Month'] == 3.0, 'Month'] = 'March'
cntryPerMonth.loc[cntryPerMonth['Month'] == 4.0, 'Month'] = 'April'
cntryPerMonth.loc[cntryPerMonth['Month'] == 5.0, 'Month'] = 'May'
and so on for the remaining months

有没有更有效的方法?

谢谢。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用字典来替换值:

    replace_dict = {
        1:'Jan', 2:'Feb'
    }
    
    
    df = pd.DataFrame({'month': [1,2]})
    
    df['month_names'] = df['month'].replace(replace_dict)
    

    【讨论】:

      猜你喜欢
      • 2018-10-16
      • 1970-01-01
      • 2019-08-07
      • 1970-01-01
      • 2021-05-21
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 2019-11-30
      相关资源
      最近更新 更多