2017-09-11 89 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)) 
相關問題