简体   繁体   English

如何按条件交换特定帧中DataFrame列的数据?

[英]How to swap data in DataFrame columns in a specific frame by condition?

for example I have the next DataFrame:例如我有下一个 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)

在此处输入图像描述

How can I swap the data in this dataframe without using cut into two dataframes and after using concatenation.如何在不使用 cut 成两个数据帧和使用串联之后交换此 dataframe 中的数据。

The replacement should occur by condition if all three values in the columns -> name, x, y is NaN如果列中的所有三个值 -> name, x, y均为NaN ,则应按条件进行替换

I try to get the next result:我尝试获得下一个结果:

在此处输入图像描述

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

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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM