Pandas:添加具有基于索引的功能的新列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34080909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:19:21 来源:igfitidea点击:
Pandas : Add new column with function based on index
提问by Mrye
Let say I have a series s
假设我有一个系列 s
index_column size
A 1
B 2
C 3
D 4
I want to add a new column contains a function f
我想添加一个包含函数的新列 f
def f(index_column):
% do something
return string
so that
以便
index_column size function(index_column)
A 1 f(A)
B 2 f(B)
C 3 f(C)
D 4 f(D)
is it possible in Series
or do I need to do that in Dataframe
?
是否有可能Series
或我需要这样做Dataframe
?
回答by Steve Misuta
Here is one way to do it with a DataFrame:
这是使用 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