python-3.x - 如何更改 Pandas 数据框中的列值?

标签 python-3.x pandas data-manipulation

我正在尝试修改数据框[列]中的值。我正在使用 slugify 来更改列中的值。

df[column][0] = "Hello-World"
df[column][1] = "Hi There!"

df[column] type is series

slugify 后的期望值

df[column][0] = "hello-world"
df[column][1] = "hi_there"

我尝试了几次迭代,但无法使其正常工作

  df[column_name] = slugify.slugify(str(df[column_name]))

上面的结果是将所有值连接成一个长字符串,并分配给列中的每一行。

我也尝试了以下但得到了与上面相同的结果。

df[column_name] = slugify.slugify((df[column_name].to_string(index=False,header=False)))

关于如何对列中的每个值应用 slugify 的任何建议。 谢谢

最佳答案

你可以直接apply slugify 函数

df.column1.apply(slugify.slugify)

在你的情况下产生

0    hello-world
1       hi-there
Name: column1, dtype: object

你原来的尝试

 slugify.slugify(str(df[column_name]))

显然是行不通的,因为 str(df[column_name]) 为整个列生成一个字符串表示形式,然后对其进行 slugified。

关于python-3.x - 如何更改 Pandas 数据框中的列值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46161670/

相关文章:

python - Pandas 有选择地删除连续的重复项

AppleScript 中的字符串操作

r - 更改 R 中数据框的多个列元素的值

python - 如何强制 Pycharm 运行所有单元测试?

python - 是否可以在棉花糖中定义具有互斥字段的嵌套模式?

python - 通过数据框与函数进行交互

python - 检查交易组之间的值是否发生变化

python - Python中如何从 'if'语句继续到 'elif'?

python - OJ 说我的 python 程序编译错误,即使它在我的计算机上运行良好(ubuntu 18.04)

python - 在 linux 上,使用 bash 脚本如何重命名 Excel 文件以在现有文件名的末尾包含行数