Ajay Shewale
Ajay Shewale

Reputation: 159

How can I swap specific column values in Dataframe?

I have a large dataframe this is the sample part of the Dataframe. Want to swap the Muscat and Shanghai values.

 df =
 City   Score

 Istanbul   6.0749
 2.23607    Muscat
 Prague     4.38576
 1.85958    Shanghai
 Istanbul   6.0749
 Singapore  5.17054

Output:

 df = 
 City   Score

 Istanbul   6.0749
 Muscat     2.23607     
 Prague     4.38576
 Shanghai   1.85958     
 Istanbul   6.0749
 Singapore  5.17054

I am confused that how can I apply the condition after iterating through the dataframe, also is there any other alternative?

Upvotes: 1

Views: 973

Answers (2)

jezrael
jezrael

Reputation: 863791

Use to_numeric with notna for boolean mask and then swap by loc:

m = pd.to_numeric(df['City'], errors='coerce').notna()
#oldier versions of pandas
#m = pd.to_numeric(df['City'], errors='coerce').notnull()
df.loc[m,['City','Score']] = df.loc[m,['Score','City']].values

print (df)
        City    Score
0   Istanbul   6.0749
1     Muscat  2.23607
2     Prague  4.38576
3   Shanghai  1.85958
4   Istanbul   6.0749
5  Singapore  5.17054

Upvotes: 4

llllllllll
llllllllll

Reputation: 16444

You can use:

In [39]: mask = pd.to_numeric(df.Score, errors='coerce').isna()

In [40]: s = df.Score.copy()

In [41]: df.Score[mask] = df.City

In [42]: df.City[mask] = s

In [43]: df
Out[43]: 
        City    Score
0   Istanbul   6.0749
1     Muscat  2.23607
2     Prague  4.38576
3   Shanghai  1.85958
4   Istanbul   6.0749
5  Singapore  5.17054

Upvotes: 2

Related Questions