Sophia
Sophia

Reputation: 71

Replace values of rows to one value in pandas dataframe

I want to replace the values of the rows of a specific column with one name, but I want to skip the rows that have no value.

enter image description here

So only the row with text in it should get a different name.

I tried this: df.loc[:, 'Groenlinks'] = 'gl' But with this all the rows change to 'gl'. I'm not sure how I can only replace the names of different rows with one word without typing all the words it should replace.

I want it to look like this:

VVD          PVV          Groenlinks
vvd                       gl
             pvv          
vvd                    
                    
vvd                       gl
vvd          pvv          

Upvotes: 0

Views: 517

Answers (2)

Shivam Roy
Shivam Roy

Reputation: 2061

If the values in the column are an empty string or they are null values, then this should work perfectly:

df['Groenlinks'].loc[df['Groenlinks'].notnull() | (df['Groenlinks'] != '')] = 'gl'

Upvotes: 2

SeaBean
SeaBean

Reputation: 23217

You can use:

df.loc[df['Groenlinks'] != '', 'Groenlinks'] = 'gl'

Empty string is not equivalent to NaN / null in Pandas. So, if you have empty string in other blank rows in the column, you can use the code above to filter the rows to set up with the new value.

Upvotes: 2

Related Questions