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?

4

2 回答 2

8

您可以使用join来进行组合:

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

如果你喜欢df*2,你可以在哪里替换。df.apply(your_function)

于 2013-01-30T12:21:44.537 回答
3

我会跳过该apply方法,直接定义列。

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

不如 DSM 的解决方案优雅。但无论出于何种原因,apply除非我真的需要它,否则我会避免使用它。

于 2013-01-30T17:19:48.050 回答