Pandas:使用基于索引的函数添加新列

时间:2015-12-04 04:26:44

标签: python pandas

假设我有一个系列s

index_column    size
A               1
B               2
C               3
D               4

我想添加一个包含函数f

的新列
def f(index_column):
    % do something
    return string

这样

index_column    size    function(index_column)
A               1       f(A)
B               2       f(B)
C               3       f(C)
D               4       f(D)

可以在Series中使用,还是需要在Dataframe中执行此操作?

1 个答案:

答案 0 :(得分:2)

以下是使用DataFrame执行此操作的一种方法:

import pandas as pd

def app_Z(s):
    """Append 'Z' onto column data"""
    return s+'Z'

# recreate the series
s = pd.Series(data=[1,2,3,4], index=['A','B','C','D'], name='Size')

# create DataFrame and apply function to column 'Index'
df = pd.DataFrame(s)
df.reset_index(inplace=True)
df.columns = ['Index', 'Size']
df['Func'] = df['Index'].apply(app_Z)
df.set_index('Index', drop=True, inplace=True)
print(df)

       Size Func 
Index           
A         1   AZ
B         2   BZ
C         3   CZ
D         4   DZ