pandas:根据第一个字符映射新值

Posted

技术标签:

【中文标题】pandas:根据第一个字符映射新值【英文标题】:pandas: map new values based on first character 【发布时间】:2016-08-28 21:46:28 【问题描述】:

有没有办法根据当前值的第一个字符将新值映射到数据框列。

我当前的代码:

ncesvars['urbantype'] = np.where(ncesvars['urbantype'].str.startswith('1'), 'city', ncesvars['urbantype'])
ncesvars['urbantype'] = np.where(ncesvars['urbantype'].str.startswith('2'), 'suburban', ncesvars['urbantype'])
ncesvars['urbantype'] = np.where(ncesvars['urbantype'].str.startswith('3'), 'town', ncesvars['urbantype'])
ncesvars['urbantype'] = np.where(ncesvars['urbantype'].str.startswith('4'), 'rural', ncesvars['urbantype'])

我在考虑使用某种dict,然后是pd.replace,但不知道如何使用.str.startswith()

【问题讨论】:

【参考方案1】:

尝试类似的方法:

ncesvars['urbantype'] = ncesvars['urbantype'].replace(
    r'^1.*', 'city', 
    r'^2.*', 'suburban',
    regex=True)

测试:

In [32]: w
Out[32]:
     word
0    1_A_
1  word03
2  word02
3  word00
4    2xxx
5  word04
6  word01
7  word02
8  word04
9    3aaa

In [33]: w['word'].replace(r'^1.*': 'city', r'^2.*': 'suburban', r'^3.*': 'town', regex=True)
Out[33]:
0        city
1      word03
2      word02
3      word00
4    suburban
5      word04
6      word01
7      word02
8      word04
9        town
Name: word, dtype: object

【讨论】:

感谢您的意见。我收到错误replace() got an unexpected keyword argument 'regex',当我在没有regex 参数的情况下尝试它时,我收到错误replace() takes at least 3 arguments (2 given) 对我也不起作用,我收到原始值 @As3adTintin,我添加了一个测试用例【参考方案2】:

您可以定义您的类别的字典,使用str[0:1] 对数据进行切片,并在Series 的布尔掩码上调用map,方法是测试数据的第一个字符是否在您的字典键中,以便仅匹配将被覆盖,否则您将使用 NaN 覆盖,因为以下示例中的最后一行没有映射:

In [16]:
df = pd.DataFrame('urbantype':['1 asdas','2 asd','3 asds','4 asdssd','5 asdas'])
df

Out[16]:
  urbantype
0   1 asdas
1     2 asd
2    3 asds
3  4 asdssd
4   5 asdas

In [18]:
d = '1':'city','2':'suburban', '3': 'town','4':'rural'
df.loc[df['urbantype'].str[0:1].isin(d.keys()), 'urbantype'] = df['urbantype'].str[0:1].map(d)
df

Out[18]:
  urbantype
0      city
1  suburban
2      town
3     rural
4   5 asdas

【讨论】:

感谢您的意见。与@ayhan 的回答相比,df.loc 部分重要吗? 是的,因为您只想影响数据与您的 dict 键匹配的行,否则您会用 NaN 覆盖该行,这就是最后一行未更改的原因

以上是关于pandas:根据第一个字符映射新值的主要内容,如果未能解决你的问题,请参考以下文章

根据每个句子的第一个单词将 pandas 数据框列中的字符串列表分解为新列

根据 pandas df 中的多个条件映射不同的数据帧

字符串中的 Pyspark 双字符替换避免某些单词而不映射到 pandas 或 rdd

Python - Pandas - 导入 Excel 文件,遍历每一行,添加新值,并添加到数据框

如何更改哈希映射中键的值? [复制]

根据序列中的位置分配新值