Pandas:添加具有基于索引的功能的新列

Mry*_*rye 5 python pandas

假设我有一个系列 s

index_column    size
A               1
B               2
C               3
D               4
Run Code Online (Sandbox Code Playgroud)

我想添加一个包含函数的新列 f

def f(index_column):
    % do something
    return string
Run Code Online (Sandbox Code Playgroud)

以便

index_column    size    function(index_column)
A               1       f(A)
B               2       f(B)
C               3       f(C)
D               4       f(D)
Run Code Online (Sandbox Code Playgroud)

是否有可能Series或我需要这样做Dataframe

Ste*_*uta 7

这是使用 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
Run Code Online (Sandbox Code Playgroud)