有没有更有效的方法将映射应用于熊猫系列?

时间:2019-04-04 16:41:46

标签: python pandas pandas-apply

我的熊猫DataFrame中有一列称为“状态”。它包含美国各州的缩写。我有硬编码的区域,我想用每个州的区域创建一个新列。

我使用了pd.Series.apply(),但是我想知道这种映射是否有更好的实践。关于如何改进代码的任何建议?

这是我当前可以使用的代码,但我只是公开征求有关最佳做法的建议。

def get_region(s, *regions):
    if s in regions[0]:
        return 'west'
    elif s in regions[1]:
        return 'midwest'
    elif s in regions[2]:
        return 'south'
    elif s in regions[3]:
        return 'northeast'
    else:
        return None

west = ['WA','OR','CA','ID','NV','MT','WY','UT','AZ','CO','NM']
midwest = ['ND','MN','WI','MI','SD','NE','KS','IA','MO','IL','IN','OH']
south = ['TX','OK','AR','LA','MS','TN','KY','AL','GA','FL','SC','NC','VA','WV','MD','DE']
northeast = ['PA','NJ','NY','CT','MA','RI','VT','NH','ME']

regions = [west,midwest,south,northeast]

full_df['Region'] = full_df['State'].apply(get_region, args=regions)
full_df['Region'].head(15)

Out:
0          west
1       midwest
2         south
3         south
4       midwest
5          west
6         south
7         south
8          west
9       midwest
10        south
11    northeast
12    northeast
13         west
14         west
Name: Region, dtype: object

2 个答案:

答案 0 :(得分:3)

使用map

进行检查
s=pd.DataFrame([west,midwest,south,northeast],index=['west','midwest','south','northeast'])
s=s.reset_index().melt('index')
full_df['Region'] = full_df['State'].map(dict(zip(s['value'],s['index'])))

答案 1 :(得分:2)

您可以尝试创建字典并将其映射到列:

west_dict = {i:"west" for i in west}
midwest_dict = {i:"midwest" for i in midwest}
south_dict = {i:"south" for i in south}
northeast_dict = {i:"northeast" for i in northeast}
d = {**west_dict, **midwest_dict, **south_dict, **northeast_dict}
full_df['Region'] = full_df['State'].map(d)