Alex T
Alex T

Reputation: 3754

Swapping columns in certain rows

I have DataFrame like this:

     A            B      C
"010-1"       "Car"     500
"010-2"     "Train"     302
"Result"      "010"      23
"011-1"      "Ship"     321
"011-2"     "Plane"     321
"011-3"      "Bike"     321
"Result"      "011"     321

Now is it possible to shift columns A and B in rows where the "Result" value is in column A using Pandas?

So that end result is:

     A            B       C
"010-1"       "Car"     500
"010-2"     "Train"     302
  "010"     "Result"     23
"011-1"      "Ship"     321
"011-2"     "Plane"     321
"011-3"      "Bike"     321
  "011"    "Result"     321

EDIT: Acutally there might be more columns than one apart from A and B

Upvotes: 3

Views: 67

Answers (3)

Akhilesh_IN
Akhilesh_IN

Reputation: 1317

try:

df['A'],df['B'] =df['A'].combine(df['B'],lambda x,y : [x,y] if x != 'Result' else [y,x]).str

Upvotes: 1

MarianD
MarianD

Reputation: 14131

You may use the numpy function where():

Original dataframe:

In[6]: df
Out[6]: 
        A      B    C
0   010-1    Car  500
1   010-2  Train  302
2  Result    010   23
3   011-1   Ship  321
4   011-2  Plane  321
5   011-3   Bike  321
6  Result    011  321

Commands:
(using common Python pattern x, y = y, x for switching values)

In[7]: cond = df.A == "Result"
In[8]: df.A, df.B = np.where(cond, df.B, df.A), np.where(cond, df.A, df.B)

Result:

In[9]: df
Out[9]: 
       A       B    C
0  010-1     Car  500
1  010-2   Train  302
2    010  Result   23
3  011-1    Ship  321
4  011-2   Plane  321
5  011-3    Bike  321
6    011  Result  321

Upvotes: 2

wwnde
wwnde

Reputation: 26676

Long hand use np.where

m=df['A'].str.contains('"Result"')
df['b']=df['B']
df['B']=np.where(m,df['A'], df['B'])
df['C']=np.where(m,df['b'], df['C'])
df.drop(columns=['b'], inplace=True)
df

enter image description here

Upvotes: 1

Related Questions