【问题标题】:map US state name to two letter acronyms that was given in dictionary separately将美国州名映射到字典中分别给出的两个字母首字母缩写词
【发布时间】:2016-11-26 01:49:54
【问题描述】:

假设现在我有一个 dataframe 有 2 列:州和城市。

然后我有一个单独的dict,每个州都有两个字母的首字母缩写词。现在我想添加第三列来映射状态名称及其两个字母的首字母缩写词。我应该在 Python/Pandas 中做什么?例如示例问题如下:

import pandas as pd
a = pd.Series({'State': 'Ohio', 'City':'Cleveland'})
b = pd.Series({'State':'Illinois', 'City':'Chicago'})
c = pd.Series({'State':'Illinois', 'City':'Naperville'})
d = pd.Series({'State': 'Ohio', 'City':'Columbus'})
e = pd.Series({'State': 'Texas', 'City': 'Houston'})
f = pd.Series({'State': 'California', 'City': 'Los Angeles'})
g = pd.Series({'State': 'California', 'City': 'San Diego'})
state_city = pd.DataFrame([a,b,c,d,e,f,g])
state_2 = {'OH': 'Ohio','IL': 'Illinois','CA': 'California','TX': 'Texas'}

现在我必须使用state_2 的字典映射df state_city 中的State 列。映射的dfstate_city 应包含三列:statecitystate_2letter

我拥有的原始数据集包含几乎所有美国主要城市的多个列。

因此,手动操作效率会降低。有什么简单的方法吗?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    一方面,将state name: abbreviation 之类的键值对存储在字典中可能更容易,如下所示:

    state_2 = {'Ohio': 'OH', 'Illinois': 'IL', 'California': 'CA', 'Texas': 'TX'}
    

    您可以轻松实现:

    state_2 = {state: abbrev for abbrev, state in state_2.items()}
    

    使用pandas.DataFrame.map

    >>> state_city['abbrev'] = state_city['State'].map(state_2)
    >>> state_city
              City       State abbrev
    0    Cleveland        Ohio     OH
    1      Chicago    Illinois     IL
    2   Naperville    Illinois     IL
    3     Columbus        Ohio     OH
    4      Houston       Texas     TX
    5  Los Angeles  California     CA
    6    San Diego  California     CA
    

    【讨论】:

    • 我们不应该把映射函数改成state_2 = {state: abbrev for state, abbrev in state_2.items()}吗?
    【解决方案2】:

    我同意@blacksite 的观点,即state_2 字典应该像这样映射它的值:

    state_2 = {'Ohio': 'OH','Illinois': 'IL','California': 'CA','Texas': 'TX'}

    然后使用pandas.DataFrame.replace

    state_city['state_2letter'] = state_city.State.replace(state_2)
    state_city
    
    |-|State      |City         |state_2letter|
    |-|-----      |------       |----------|
    |0| Ohio      | Cleveland   |   OH|
    |1| Illinois  | Chicago     |   IL|
    |2| Illinois  | Naperville  |   IL|
    |3| Ohio      | Columbus    |   OH|
    |4| Texas     | Houston     |   TX|
    |5| California| Los Angeles |   CA|
    |6| California| San Diego   |   CA|
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-21
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多