Feng Xinmei
Feng Xinmei

Reputation: 1

How to move just two columns of pandas dataframe to specific positions?

I have a dataset of 100 columns like follows:

citycode AD700 AD800 AD900 ... AD1980 countryname cityname

I want the output dataframe to have columns as follows:

citycode countryname cityname AD700 AD800 AD900 ... AD1980 

I can't use code like

cols = [A, B, C, D, E]
df = df[cols]

because it would be too cumbersome. Thank you!

Upvotes: 0

Views: 26

Answers (1)

Valdi_Bo
Valdi_Bo

Reputation: 30991

One of possible solutions is:

df = df[['citycode', 'countryname', 'cityname'] + list(df.loc[:, 'AD700':'AD1980'])]

Note that you compose the list of column names from:

  • a "by name" list (first 3),
  • a "by range" list (all other columns).

This way, from a source DataFrame like:

  citycode  AD700  AD800  AD900  AD1980 countryname cityname
0      CC1     10     20     30      40         CN1      CT1
1      CC2     11     21     31      41         CN2      CT2

you will get:

  citycode countryname cityname  AD700  AD800  AD900  AD1980
0      CC1         CN1      CT1     10     20     30      40
1      CC2         CN2      CT2     11     21     31      41

Upvotes: 1

Related Questions