【发布时间】: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()
【问题讨论】:
标签: python-2.7 pandas dictionary replace dataframe