【问题标题】:How to add columns using a dictionary in python pandas如何在 python pandas 中使用字典添加列
【发布时间】:2020-11-14 03:14:02
【问题描述】:

我想在数据框中使用字典键添加一列 这是我尝试的当前代码,但它没有返回行政区而是为所有人返回“其他”

boroughs = {'Manhattan':[1, 2, 3], 
            'Bronx':[4, 5, 6], 
            'Brooklyn':[7, 8, 9],
            'Staten Island': 10}

def test(x):
  for key, value in boroughs.items():
    if int(x) in value or int(x) == value:
      return key
    else:
      return 'Other'
      
df['Boroughs'] = df.precinct.apply(test)

我运行代码后,这是当前的自治市镇

precinct   Boroughs
1.0        'Other'
5.0        'Other'
9.0        'Other'
10.0       'Other'

这是预期的结果

precinct   Boroughs
1.0        'Manhattan'
5.0        'Bronx'
9.0        'Brooklyn'
10.0       'Staten Island'

我想知道我哪里弄错了提前谢谢

【问题讨论】:

    标签: python python-3.x pandas dataframe dictionary


    【解决方案1】:

    你的 dict 是倒退的。试试这个:

    boroughs = {
        'Manhattan': [1, 2, 3], 
        'Bronx': [4, 5, 6], 
        'Brooklyn': [7, 8, 9],
        'Staten Island': [10],
    }
    
    d = {}
    for k, v in boroughs.items():
        for num in v:
            d[num] = k
    
    df["Boroughs"] = df.precinct.astype(int).map(d)
    

    输出:

       precinct       Boroughs
    0       1.0      Manhattan
    1       5.0          Bronx
    2       9.0       Brooklyn
    3      10.0  Staten Island
    

    旁注:不保证 dicts 是可逆的。在这里,我假设每个区域都与一个独特的自治市镇相关联。

    【讨论】:

    • 谢谢!!这解决了我的问题!我对 map 不太了解,我可能稍后会检查它们,双循环对我来说似乎是合乎逻辑的,但我可能仍然对我的原始代码错误感到困惑。
    • 当您知道键并想要值时,字典很有用 - 在您的情况下,您知道区域并想要自治市镇。我所做的只是反转提供的字典。至于map:它只是用数据框中的值替换键。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-29
    • 2023-02-23
    • 2020-12-04
    • 2022-01-11
    • 2018-07-22
    • 1970-01-01
    • 2016-09-25
    相关资源
    最近更新 更多