У меня есть следующий DataFrame:
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?
Используйте переименовать в 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
Это должно сделать:
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
Pandas reindex может помочь:
reindex
cols = df.columns #reposition the columns df = df.reindex(columns=['col1','col4','col5','col2','col3']) #pass in new names df.columns = cols
Если вы хотите поменять местами значения столбцов:
df.iloc[:, 1:3], df.iloc[:, 3:] = df.iloc[:,3:].to_numpy(copy=True), df.iloc[:,1:3].to_numpy(copy=True)