2024-04-29 09:19:16 发布
网友
我有一个数据帧看起来像
ID Name 0 1 USA State 1 2 Canada 2 3 Egypt 3 4 Titicaca State ...
我想用S替换所有State。所以结果应该是
S
State
我试过了
DF.loc["State" in DF['Name']] = "S"
但是得到了KeyError: 'cannot use a single bool to index into setitem'
KeyError: 'cannot use a single bool to index into setitem'
您可以使用str.replace方法,它可以替换regex模式。这里使用\bState\b匹配单词State,并将其替换为S:
str.replace
\bState\b
df['Name'] = df.Name.str.replace(r"\bState\b", "S") df # ID Name #0 1 USA S #1 2 Canada #2 3 Egypt #3 4 Titicaca S
您可以使用
str.replace
方法,它可以替换regex模式。这里使用\bState\b
匹配单词State
,并将其替换为S
:相关问题 更多 >
编程相关推荐