Python pandas 替换列中的值

标签 python pandas dataframe replace

当我查看数据框中的列中的值时,我可以看到由于用户数据输入错误,相同的类别输入不正确。

对于我的数据框,我使用以下代码:

df['column_name'].value_counts()

输出:

 Targeted    523534
 targeted    1
 story       25425
 story       2
 multiple    2524543

对于故事,我想有一个空格?

我正在尝试将 Targeted 替换为 Targeted。

df['column_name'].replace("targeted","Targeted")

但是什么也没有发生,我仍然得到相同的值计数。

最佳答案

是的,似乎有开头和结尾的空白。

需要str.strip先然后Series.replaceSeries.str.replace :

df['column_name'] = df['column_name'].str.strip().replace("targeted","Targeted")

df['column_name'] = df['column_name'].str.strip().str.replace("targeted","Targeted")

另一种可能的解决方案是将所有字符转换为小写:

df['column_name'] = df['column_name'].str.strip().str.lower()

关于Python pandas 替换列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42121598/

相关文章:

python - 在 Python Pandas 中格式化字符串数字

python - 这是基于 django 类的 View 的错误使用吗?

python在excel中读取大整数

python - 在散点图中,我想自动填充轴

Python:是否可以抓取一个非常特定的网页?

python - Pandas:如何扩展包含列中具有不同键的字典的数据框行?

python - 查找 pandas 数据帧的列和行中所有重复模式的所有索引/实例

python - 无法使用 resample.ohlc() 方法 - DataError : No numeric types to aggregate

python - 对 pandas DataFrame 中的空值使用 None 而不是 np.nan

python - 处理过多的零