Home > Back-end >  How to swap data in DataFrame columns in a specific frame by condition?
How to swap data in DataFrame columns in a specific frame by condition?

Time:12-29

for example I have the next DataFrame:

data = [{'name': 'test', 'x': 'test', 'y': 'test', 'name_2': np.NaN, 'x_2': np.NaN, 'y_2': np.NaN}, {'name': 'test', 'x': 'test', 'y': 'test', 'name_2': np.NaN, 'x_2': np.NaN, 'y_2': np.NaN}, {'name': 'test', 'x': 'test', 'y': 'test', 'name_2': np.NaN, 'x_2': np.NaN, 'y_2': np.NaN}, {'name': 'test', 'x': 'test', 'y': 'test', 'name_2': 'test', 'x_2': 'test', 'y_2': 'test'}, {'name': 'test', 'x': 'test', 'y': 'test', 'name_2': 'test', 'x_2': 'test', 'y_2': 'test'}, {'name': 'test', 'x': 'test', 'y': 'test', 'name_2': 'test', 'x_2': 'test', 'y_2': 'test'}, {'name': 'test', 'x': 'test', 'y': 'test', 'name_2': 'test', 'x_2': 'test', 'y_2': 'test'}, {'name': np.NaN, 'x': np.NaN, 'y': np.NaN, 'name_2': 'test', 'x_2': 'test', 'y_2': 'test'}, {'name': np.NaN, 'x': np.NaN, 'y': np.NaN, 'name_2': 'test', 'x_2': 'test', 'y_2': 'test'}, {'name': np.NaN, 'x': np.NaN, 'y': np.NaN, 'name_2': 'test', 'x_2': 'test', 'y_2': 'test'}]

df = pd.DataFrame(data)
    print(df)

enter image description here

How can I swap the data in this dataframe without using cut into two dataframes and after using concatenation.

The replacement should occur by condition if all three values in the columns -> name, x, y is NaN

I try to get the next result:

enter image description here

CodePudding user response:

We can do it step by step

l = ['name','x','y']
s = ['name_2','x_2','y_2']
cond = df[l].isna().all(1)
df.loc[cond,l] = df.loc[cond,s].values
df.loc[cond,s] = np.nan
df
Out[57]: 
   name     x     y name_2   x_2   y_2
0  test  test  test    NaN   NaN   NaN
1  test  test  test    NaN   NaN   NaN
2  test  test  test    NaN   NaN   NaN
3  test  test  test   test  test  test
4  test  test  test   test  test  test
5  test  test  test   test  test  test
6  test  test  test   test  test  test
7  test  test  test    NaN   NaN   NaN
8  test  test  test    NaN   NaN   NaN
9  test  test  test    NaN   NaN   NaN

CodePudding user response:

In a rather similar vein, you can try:

df[['name', 'x', 'y']] = df[['name', 'x', 'y']].mask(df[['name', 'x', 'y']].isna().all(axis=1), df[['name_2', 'x_2', 'y_2']].to_numpy())
  • Related