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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

BY avoiding the join this also has the nice benefit of not having to reassign the dataframe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.