以同时处理两列数据为例,将两列中的数据相加,生成另外一列:
import pandas as pd
df = pd.DataFrame({'a': np.random.randn(6),
'b': ['foo', 'bar'] * 3,
'c': np.random.randn(6)})
print(df)
def add(a, b):
return a + b
df['Value'] = df.apply(lambda x: add(x['a'], x['c']), axis=1)
print(df)
输出结果:
a b c
0 0.855374 foo 0.596161
1 0.176524 bar -1.598799
2 0.270245 foo -0.600968
3 0.958155 bar -0.097909
4 0.480277 foo -0.340813
5 -0.548556 bar 0.341068
a b c Value
0 0.855374 foo 0.596161 1.451535
1 0.176524 bar -1.598799 -1.422275
2 0.270245 foo -0.600968 -0.330723
3 0.958155 bar -0.097909 0.860246
4 0.480277 foo -0.340813 0.139464
5 -0.548556 bar 0.341068 -0.207488
本文通过实例演示了如何使用Python的Pandas库处理数据表,具体介绍了如何对数据表中的两列数值进行相加操作,并生成新的列。通过定义一个简单的函数add(),并利用apply()方法沿axis=1方向应用此函数,实现了对每行数据中特定两列的数值相加。
1万+

被折叠的 条评论
为什么被折叠?



