简体   繁体   中英

Creating columns in pandas dataframe and assign values

I have a pandas dataframe as below:

df = pd.DataFrame({'group': [1, 1, 1, 1, 1, 1, 2, 2, 2, 2],
                    'A2_BAL': [1,2,1,5,7,5,4,1,8,10],
                     'A1_BAL': [10,20,10,50,70,50,40,10,80,100]})
df

group   A2_BAL  A1_BAL
0       1       10
1       2       20
2       1       10
3       5       50
4       7       70
5       5       50
6       4       40
7       1       10
8       8       80
9       10      100 

and a list as below

list = [A2, A1] 

I need to create columns based on the elements in the list(A2_AGG, A1_AGG) and assign the value of 'A2_BAL' and 'A1_BAL'

My expected outout should look as below

group   A2_BAL  A1_BAL  A2_AGG  A1_AGG
0       1       10      1       10 
1       2       20      2       20 
2       1       10      1       10 
3       5       50      5       50 
4       7       70      7       70 
5       5       50      5       50 
6       4       40      4       40 
7       1       10      1       10 
8       8       80      8       80 
9       10      100     10      100

I don't want to hard-code this because the elements in the list and column name may vary.

I tried the below code but dont know how to assign "df[i]"

new_list = [t + '_agg' for t in list]
for i in new_list:
    df[i]  = np.nan
df

If you use the string from the list as a variable you can dynamically assign columns:

for colname in list:
    df[f'{colname}_AGG'] = df[f'{colname}_BAL']

This uses Python 3.6's f-strings to combine variable and strings in an easy way.

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