简体   繁体   English

使用函数pandas python基于来自其他列的值添加新列

[英]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.

相关问题 基于python pandas中其他列的值创建新列 - Creating a new column based on values from other columns in python pandas Python Pandas 基于其他列值的新列 - Python Pandas New Column based on values from other columns python:pandas:按条件将其他 dataframe 的值添加到新列中 - python: pandas: add values from other dataframe into new column by condition 根据其他列(python)中的分类值创建新的pandas列 - Create new pandas column based on categorical values in other column (python) Pandas/Python:如何根据其他列的值创建新列并将额外条件应用于此新列 - Pandas/Python: How to create new column based on values from other columns and apply extra condition to this new column 根据另一列中的值将列添加到Python pandas DataFrame - Add column to a Python pandas DataFrame based on values in an other column 根据 Pandas 中其他列的一些值创建一个新列 - Create a New Column Based on Some Values From Other Column in Pandas 根据其他列中的值使用 pandas 添加计算列 - add calculated column using pandas based on values in other column 根据 pandas 中字典中另一列的值添加新列 - Add new column based on values of another column from a dictionary in pandas 根据来自其他列 pandas python 的特定值创建一列 - Make a column based on specific values from other column pandas python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM