Как переключать значения столбцов в одном Pandas DataFrame - PullRequest
2 голосов
/ 07 августа 2020

У меня есть следующий DataFrame:

enter image description here

I need to switch values of col2 and col3 with the values of col4 and col5. Values of col1 will remain the same. The end result needs to look as the following:

введите описание изображения здесь

Есть ли способ сделать это без цикла через DataFrame?

Ответы [ 4 ]

3 голосов
/ 07 августа 2020

Используйте переименовать в pandas

In [160]: df = pd.DataFrame({'A':[1,2,3],'B':[3,4,5]})

In [161]: df
Out[161]:
   A  B
0  1  3
1  2  4
2  3  5

In [167]: df.rename({'B':'A','A':'B'},axis=1)
Out[167]:
   B  A
0  1  3
1  2  4
2  3  5
3 голосов
/ 07 августа 2020

Это должно сделать:

og_cols = df.columns
new_cols = [df.columns[0], *df.columns[3:], *df.columns[1:3]]
df = df[new_cols] # Sort columns in the desired order
df.columns = og_cols # Use original column names
1 голос
/ 07 августа 2020

Pandas reindex может помочь:

cols = df.columns

#reposition the columns
df = df.reindex(columns=['col1','col4','col5','col2','col3'])
#pass in new names
df.columns = cols
1 голос
/ 07 августа 2020

Если вы хотите поменять местами значения столбцов:

df.iloc[:, 1:3], df.iloc[:, 3:] = df.iloc[:,3:].to_numpy(copy=True), df.iloc[:,1:3].to_numpy(copy=True)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...