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?
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.
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.
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.