简体   繁体   中英

Creating new column from other columns in pandas dataframe

I have a dataframe

   2019Q4  2020Q4
0      20      10
1      56      15
2      63      14

from this dataframe i wanted to create

   2019Q4  2020Q4  year2019  year2020
0      20      10        20        10
1      56      15        56        15
2      63      14        63        14

please help how I can acheive this in python

Use rename with lambda function for first 4 values, add prefix by DataFrame.add_prefix and then add to original by DataFrame.join :

df = df.join(df.rename(columns=lambda x: x[:4]).add_prefix('year'))
print (df)
   2019Q4  2020Q4  year2019  year2020
0      20      10        20        10
1      56      15        56        15
2      63      14        63        14

If possible multiple columns with same year:

print (df)
   2019Q4  2020Q4  2020Q3
0      20      10       3
1      56      15       5
2      63      14      15


df1 = df.join(df.rename(columns=lambda x: x[:4]).add_prefix('year'))
print (df1)
   2019Q4  2020Q4  2020Q3  year2019  year2020  year2020
0      20      10       3        20        10         3
1      56      15       5        56        15         5
2      63      14      15        63        14        15

If select one column get all columns, because duplicated:

print (df1['year2020'])
   year2020  year2020
0        10         3
1        15         5
2        14        15

Possible solution is aggregate, eg by sum :

df1 = df.join(df.groupby(lambda x: x[:4], axis=1).sum().add_prefix('year'))
print (df1)
   2019Q4  2020Q4  2020Q3  year2019  year2020
0      20      10       3        20        13
1      56      15       5        56        20
2      63      14      15        63        29

if you are new to pandas than you can also use below code:

df1['year2019']=df1['2019Q4']
df1['year2020']=df1['2020Q4']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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