[英]add a new column based on values from other column using a function pandas python
I have a dataframe and I want to add a new column based on some processing on an existing column. 我有一个数据框,我想根据现有列上的一些处理添加一个新列。
import pandas as pd
def func_processcol(l):
processedl=l+1
return processedl
df = pd.DataFrame({'a':['l1','l2','l3','l4','l5','l6'],
'b':['1','2','2','1','2','2']})
Now I want to add a new column to dataframe by passing the values in column a . 现在,我想通过传递列a中的值向数据框添加新列。 df[e]=[l1+1, ....] df [e] = [l1 + 1,....]
I think you need apply
: 我想你需要apply
:
def func_processcol(l):
#changed `1` to string for correct output
processedl=l + '1'
return processedl
df = pd.DataFrame({'a':['l1','l2','l3','l4','l5','l6'],
'b':['1','2','2','1','2','2']})
df['c'] = df.b.apply(func_processcol)
print (df)
a b c
0 l1 1 11
1 l2 2 21
2 l3 2 21
3 l4 1 11
4 l5 2 21
5 l6 2 21
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.