3

I have a pandas DataFrame like:

          A    B  
'2010-01-01'  10  20   
'2010-02-01'  20  30  
'2010-03-01'  30  10  

I need to apply some function for every columns and create new columns in this DataFrame with special name.

               A   B A1 B1  
'2010-01-01'  10  20 20 40  
'2010-02-01'  20  30 40 60  
'2010-03-01'  30  10 60 20

So I need to make two additional columns with names A1 and B2 based on columns A and B ( like name A1 = str(A) + str(1)) by multiplying by two. Is it possible to do this using DataFrame.apply() or other construction?

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
Vitali Molchan
  • 203
  • 4
  • 9

2 Answers2

8

You can use join to do the combining:

>>> import pandas as pd
>>> df = pd.DataFrame({"A": [10,20,30], "B": [20, 30, 10]})
>>> df
    A   B
0  10  20
1  20  30
2  30  10
>>> df * 2
    A   B
0  20  40
1  40  60
2  60  20
>>> df.join(df*2, rsuffix='1')
    A   B  A1  B1
0  10  20  20  40
1  20  30  40  60
2  30  10  60  20

where you could replace df*2 with df.apply(your_function) if you liked.

DSM
  • 342,061
  • 65
  • 592
  • 494
3

I would skip the apply method and just define the columns directly.

import pandas as pd
df = pd.DataFrame({"A": [10,20,30], "B": [20, 30, 10]})
for col in df.columns:
    df[col+"1"] = df[col] * 2

Not as elegant as DSM's solution. But for whatever reason I avoid apply unless I really need it.

Paul H
  • 65,268
  • 20
  • 159
  • 136