Babaji
Babaji

Reputation: 408

Swapping of elements in a PANDAS dataframe

Given below is a table :

    A NUMBER    B NUMBER
    7042967611  9999574081
    12320       9999574081
    9999574081  9810256463
    9999574081  9716551924
    9716551924  9999574081  
    9999574081  8130945859

This was originally an excel sheet which has been converted into a dataframe. I wish to swap some of the elements such that the A number column has only 9999574081. Therefore the output should look like :

    A NUMBER    B NUMBER
    9999574081  7042967611  
    9999574081  12320       
    9999574081  9810256463
    9999574081  9716551924
    9999574081  9716551924  
    9999574081  8130945859

This is the code I have used :

for i in list(df['A NUMBER']):
    j=0
    if i!= 9999574081:
        temp = df['B NUMBER'][j]
        df['B NUMBER'][j] = i
        df['A NUMBER'][j] = temp
    j+=1

However, I am not getting the desired result. Please help me out. Thanks:)

Upvotes: 3

Views: 622

Answers (1)

jezrael
jezrael

Reputation: 862611

Use DataFrame.loc for swap only rows matched boolean mask, values is necessary for avoid align index values:

m = df['A NUMBER'] != 9999574081

df.loc[m, ['A NUMBER','B NUMBER']] = df.loc[m, ['B NUMBER','A NUMBER']].values

Another solution with numpy.where:

df['B NUMBER'] = np.where(df['A NUMBER'] != 9999574081, df['A NUMBER'], df['B NUMBER'])
df['A NUMBER'] = 9999574081

print (df)
     A NUMBER    B NUMBER
0  9999574081  7042967611
1  9999574081       12320
2  9999574081  9810256463
3  9999574081  9716551924
4  9999574081  9716551924
5  9999574081  8130945859

Upvotes: 1

Related Questions