2017-09-11 91 views
1

我正在尝试修改数据框[列]中的值。我正在使用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列中的每个值。 感谢

回答

1

你可以直接applyslugify功能

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字符串表示。

1

你可以尝试

from slugify import slugify 
df['column_name'] = df['column'].apply(lambda x :slugify(x)) 
相关问题