使用apply()函数在pandas.DataFrame中创建新列 [英] Creating of new columns in pandas.DataFrame using apply() function

查看:600
本文介绍了使用apply()函数在pandas.DataFrame中创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫DataFrame,如:

I have a pandas DataFrame like:

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

我需要为每个列应用一些功能,并在此DataFrame中使用特殊名称创建新列.

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

因此,我需要根据列AB(例如名称A1 = str(A) + str(1))乘以2,以得到另外两个名称分别为A1B2的列.是否可以使用DataFrame.apply()或其他结构来做到这一点?

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?

推荐答案

您可以使用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).

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

这篇关于使用apply()函数在pandas.DataFrame中创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆