gpt4 book ai didi

python - 使用 np.where() 将 Pandas 数据框中的 True/False 值更改为离散值

转载 作者:太空宇宙 更新时间:2023-11-03 15:00:14 24 4
gpt4 key购买 nike

我正在尝试将州名分配给大学名称列表:

df = pd.DataFrame({'College': pd.Series(['University of Michigan', 'University of Florida', 'Iowa State'])})
State = ['Michigan', 'Iowa']
df['State'] = np.where(df['College'].str.contains('|'.join(State)),
'state','--')

我想用州的实际名称替换出现的“州”值。示例:密歇根大学 -> 密歇根(而不是“州”)。最终,“State”将包含所有 50 个州,因此我无法为每个州名称编写 50 个“np.where”语句。

感谢您的帮助。

最佳答案

你可以在这里使用str.extract,而不是np.where:

In [290]: df['State'] = df['College'].str.extract('({})'.format('|'.join(State)), expand=True)

In [291]: df
Out[291]:
College State
0 University of Michigan Michigan
1 University of Florida NaN
2 Iowa State Iowa

关于python - 使用 np.where() 将 Pandas 数据框中的 True/False 值更改为离散值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38622487/

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