创建新列

Creating new column

我有一个数据框

id_drill depth
454_001   5
456_013   6
454_0078  8.5
455_012   3
00D12_212 4
5G18_356  6
5G15_40   9.1

我正在尝试将列 city 添加到 pd dataframe 如果id_drill列中的字符串以来自2个不同dict的键开头,那么添加的值应该是那个dict的键的值。但是当我使用 or 条件时它不起作用?

city_old = {'454': 'NYC', '455':"Montreal" , '456': 'Toronto'}
city_new = {'00D12': 'NYC', '5G15':"Montreal" , '5G18': 'Toronto'}

for (k,v), (k2,v2) in zip(city_old.items(), city_new.items()):
    try:
        df.loc[(df['id_drill'].str.startswith(k) ==True) or (df['id_drill'].str.startswith(k2) ==True), 'city'] = v2
        
    except ValueError:
        pass

这是我除了 :

之外的结果
id_drill depth  city
454_001   5     NYC
456_013   6     Toronto
454_0078  8.5   NYC
455_012   3     Montreal
00D12_212 4     NYC
5G18_356  6     Toronto
5G15_40   9.1   Montreal

有什么想法吗?

谢谢

首先使用 dict 解包合并两个字典,然后使用 Series.str.split + Series.str.map 将合并字典中的值映射到列 id_drill:

中的字符串
m = {**city_old, **city_new}
df['city'] = df['id_drill'].str.split('_').str[0].map(m)

结果:

    id_drill  depth      city
0    454_001    5.0       NYC
1    456_013    6.0   Toronto
2   454_0078    8.5       NYC
3    455_012    3.0  Montreal
4  00D12_212    4.0       NYC
5   5G18_356    6.0   Toronto
6    5G15_40    9.1  Montreal