Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change column values in dataframe in pandas?

I am trying to modify the values in a dataframe[column]. I am using slugify to change the values in column.

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

df[column] type is series

Expected value after slugify

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

I tried couple of iterations but cannot get it to work correctly

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

The above resulted in concatenation of all values into a long string and being assigned to each row in the column.

I also tried the following but the got the same result as above.

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

Any suggestions how can i apply slugify on each value in the column. Thanks

like image 632
jsp Avatar asked Dec 08 '25 18:12

jsp


2 Answers

You can just directly apply the slugify function

df.column1.apply(slugify.slugify)

which in your case yields

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

Your original attempt of

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

evidently won't work, because str(df[column_name]) yields a string representation for the entire column, which is then slugified.

like image 98
miradulo Avatar answered Dec 10 '25 23:12

miradulo


Can you try

from slugify import slugify
df['column_name'] = df['column'].apply(lambda x :slugify(x))
like image 29
Spandan Brahmbhatt Avatar answered Dec 10 '25 21:12

Spandan Brahmbhatt