用列中的不同值替换多个字符串值 (python)
replace multiple string values with different values in a column (python)
这是一个示例数据集:
ID
Description
1
he wants some epples
2
she bought 2kgs of bakana
3
he got nothing
4
she took potato and tomat
我想这样替换它:
df['Description']= df['Description'].str.replace({'epples':'apples','bakana':'banana','tomat':'tomato'})
返回错误:
TypeError:replace() 缺少 1 个必需的位置参数:'repl'
我该怎么做才能达到这个结果:
ID
Description
1
he wants some apples
2
she bought 2kgs of banana
3
he got nothing
4
she took potato and tomato
是的,在 str.replace(something, toReplaceWith)
中,您错过了 toReplaceWith
,因此它出错了
这样试试:
import pandas as pd
df = pd.DataFrame({'ID':[1,2,3,4], 'Description':['he wants some epples', 'she bought 2kgs of bakana', 'he got nothing', 'she took potato and tomat']})
replacement = {
"epples": "apples",
"bakana": "banana",
"tomat": "tomato"
}
print(df['Description'].replace(replacement, regex=True))
输出:
0 he wants some apples
1 she bought 2kgs of banana
2 he got nothing
3 she took potato and tomato
这是一个示例数据集:
ID | Description |
---|---|
1 | he wants some epples |
2 | she bought 2kgs of bakana |
3 | he got nothing |
4 | she took potato and tomat |
我想这样替换它:
df['Description']= df['Description'].str.replace({'epples':'apples','bakana':'banana','tomat':'tomato'})
返回错误:
TypeError:replace() 缺少 1 个必需的位置参数:'repl'
我该怎么做才能达到这个结果:
ID | Description |
---|---|
1 | he wants some apples |
2 | she bought 2kgs of banana |
3 | he got nothing |
4 | she took potato and tomato |
是的,在 str.replace(something, toReplaceWith)
中,您错过了 toReplaceWith
,因此它出错了
这样试试:
import pandas as pd
df = pd.DataFrame({'ID':[1,2,3,4], 'Description':['he wants some epples', 'she bought 2kgs of bakana', 'he got nothing', 'she took potato and tomat']})
replacement = {
"epples": "apples",
"bakana": "banana",
"tomat": "tomato"
}
print(df['Description'].replace(replacement, regex=True))
输出:
0 he wants some apples
1 she bought 2kgs of banana
2 he got nothing
3 she took potato and tomato