如果lis中有文本,则用值替换某些文本

2024-10-03 23:22:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是在了解熊猫的情况,不能解决一个问题。我有一份纽约州的县名单。如果这个县是5个行政区之一,我想把这个县的名字改成纽约,否则我就不管了。下面给出了这个想法,但并不正确。你知道吗

编辑-因此,如果县列中的前几行县是奥尔巴尼,阿勒格尼,布朗克斯前的变化,他们将奥尔巴尼,阿勒格尼,纽约后的变化

# clean up county names
# 5 boroughs must be combined to New York City
# eliminate the word county
nyCounties = ["Kings", "Queens", "Bronx", "Richmond", "New York"]

nypopdf['County'] = ['New York' for nypopdf['County'] in nyCounties else   
nypopdf['County']]

Tags: clean编辑newnames情况名字行政区up
1条回答
网友
1楼 · 发布于 2024-10-03 23:22:46

小模型:

In [44]: c = ['c', 'g']
In [45]: df = pd.DataFrame({'county': list('abccdefggh')})
In [46]: df['county'] = df['county'].where(~df['county'].isin(c), 'N')
In [47]: df
Out[47]:   county
         0      a
         1      b
         2      N
         3      N
         4      d
         5      e
         6      f
         7      N
         8      N
         9      h

因此,这是使用pd.Series.where~df['county'].isin(c)选择不在列表中的行c(开始处的~是'not'操作),第二个参数是要替换的值(当条件为False时)。你知道吗

为了符合您的示例:

nypopdf['County'] = nypopdf['County'].where(~nypopdf['County'].isin(nyCounties), 'New York')

或者

nypopdf['County'].where(~nypopdf['County'].isin(nyCounties), 'New York', inplace=True)

完整示例:

nypopdf = pd.DataFrame({'County': ['Albany', 'Allegheny', 'Bronx']})
nyCounties = ["Kings", "Queens", "Bronx", "Richmond", "New York"]
print(nypopdf)
      County
0     Albany
1  Allegheny
2      Bronx
nypopdf['County'].where(~nypopdf['County'].isin(nyCounties), 'New York', inplace=True)
print(nypopdf)
      County
0     Albany
1  Allegheny
2   New York

相关问题 更多 >