gpt4 book ai didi

python - 使用 Pandas 将多个值替换为单个值

转载 作者:行者123 更新时间:2023-11-28 22:30:29 26 4
gpt4 key购买 nike

我有一个各种值的列表,我需要将其替换为单个值(Drive-by)。我做了我的研究,但我能找到的最接近的帖子是下面的附加链接,它没有使用 Pandas。实现这一目标的最可行方法是什么?

Python replace multiple strings

fourth = pd.read_csv('C:/infocentertracker.csv')
fourth = fourth.rename(columns={'Phone Number: ': 'Phone Number:'})
fourth['Source:'] = fourth['Source:'].replace('......', 'Drive-by')

fourth.to_csv(.............)

Drive By
Drive-By
Drive-by; Return Visitor
Drive/LTX.com/Internes Srch Replace all with Drive-by
Driving By/Lantana Website
Drive by
Driving By/Return Visitor
Drive by/Resident Referral
Driving by
Drive- by
Driving by/LTX Website
Driving By
Driving by/Return Visitor
Drive By/Return Visitor
Drive By/LTX Website

最佳答案

您可以通过 str.startswith 使用 bool 掩码用于替换所有以 Driv 开头的值,想法来自 comment of Marat :

df.loc[df.col.str.startswith('Driv'), 'col'] = 'Drive-by'

示例:

print (fourth)
col
0 Drive By
1 Drive-By
2 Drive-by; Return Visitor
3 Drive/LTX.com/Internes Srch
4 Driving By/Lantana Website
5 Drive by
6 Driving By/Return Visitor
7 Drive by/Resident Referral
8 Driving by
9 Drive- by
10 Driving by/LTX Website
11 Driving By
12 Driving by/Return Visitor
13 Drive By/Return Visitor
14 Drive By/LTX Website
15 aaa
fourth.loc[fourth['Source:'].str.startswith('Driv'), 'Source:'] = 'Drive-by'
print (fourth)
Source:
0 Drive-by
1 Drive-by
2 Drive-by
3 Drive-by
4 Drive-by
5 Drive-by
6 Drive-by
7 Drive-by
8 Drive-by
9 Drive-by
10 Drive-by
11 Drive-by
12 Drive-by
13 Drive-by
14 Drive-by
15 aaa

另一种解决方案 Series.mask :

fourth['Source:']=fourth['Source:'].mask(fourth['Source:'].str.startswith('Driv', na=False),
'Drive-by')
print (fourth)
Source:
0 Drive-by
1 Drive-by
2 Drive-by
3 Drive-by
4 Drive-by
5 Drive-by
6 Drive-by
7 Drive-by
8 Drive-by
9 Drive-by
10 Drive-by
11 Drive-by
12 Drive-by
13 Drive-by
14 Drive-by
15 aaa

关于python - 使用 Pandas 将多个值替换为单个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42161704/

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