我是 Pandas 新手。我的数据集中有以下数据类型。 (数据集是从 Kaggle 下载的 Indian Startup Funding。)
Date datetime64[ns]
StartupName object
IndustryVertical object
CityLocation object
InvestorsName object
InvestmentType object
AmountInUSD object
dtype: object
data['AmountInUSD'].groupby(data['CityLocation']).describe()
我做了上面的操作,发现很多城市都是类似的,例如,
Bangalore
Bangalore / Palo Alto
Bangalore / SFO
Bangalore / San Mateo
Bangalore / USA
Bangalore/ Bangkok
我想做以下操作,但我不知道代码。
在 CityLocation 列中,查找以“Bang”开头的所有单元格,并将其全部替换为“Bangalore”。我们将不胜感激。
我做到了
data[data.CityLocation.str.startswith('Bang')]
我不知道之后该做什么。
最佳答案
您可以使用 loc
函数查找列中子字符串匹配的值,并将其替换为您选择的值。
import pandas as pd
df = pd.DataFrame({'CityLocation': ['Bangalore', 'Dangerlore', 'Bangalore/USA'], 'Values': [1, 2, 3]})
print(df)
# CityLocation Values
# 0 Bangalore 1
# 1 Dangerlore 2
# 2 Bangalore/USA 3
df.loc[df.CityLocation.str.startswith('Bang'), 'CityLocation'] = 'Bangalore'
print(df)
# CityLocation Values
# 0 Bangalore 1
# 1 Dangerlore 2
# 2 Bangalore 3
关于python - 如何替换 pandas 数据框中看起来相似的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51032814/