gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 17:52:11 24 4
gpt4 key购买 nike

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

我当前的代码:

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( )

最佳答案

尝试类似的操作:

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

关于python-2.7 - pandas:根据第一个字符映射新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37011055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com