Pandas 系列是带有轴标签的一维ndarray。标签不必是唯一的,但必须是可哈希的类型。该对象同时支持基于整数和基于标签的索引,并提供了许多方法来执行涉及索引的操作。
Pandas Series.transform()函数在self上调用func(传递的函数),生成具有转换后的值的序列,并且该序列具有与self相同的轴长。
用法: Series.transform(func, axis=0, *args, **kwargs)
参数:
func:如果是函数,则必须在传递Series或传递给Series.apply时起作用
axis:与DataFrame兼容所需的参数。
*参数:位置参数传递给func。
** kwargs:传递给func的关键字参数。
返回:返回必须与自身长度相同的序列。
范例1:采用Series.transform()函数来转换给定Series对象的元素。在每个城市名称的末尾附加“ _City”。
# importing pandas as pd
import pandas as pd
# Creating the Series
sr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])
# Create the Datetime Index
didx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W',
periods = 6, tz = 'Europe/Berlin')
# set the index
sr.index = didx
# Print the series
print(sr)
输出:
现在我们将使用Series.transform()函数在每个城市名称的末尾附加“ _City”。
# append '_City'
sr.transform(lambda x:x + '_City')
输出:
正如我们在输出中看到的,Series.transform()功能已成功在所需城市名称的末尾附加了所需的关键字。
范例2:采用Dataframe.transform()函数转换给定 DataFrame 的数据。甚至将每张门票的价格增加1000。
# importing pandas as pd
import pandas as pd
# Creating the Dataframe
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],
'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],
'Cost':[10000, 5000, 15000, 2000]})
# Print the dataframe
print(df)
输出:
现在我们将使用Dataframe.transform()功能将机票成本增加1000
# transform the 'Cost' column
df['Cost'] = df['Cost'].transform(lambda x:x + 1000)
# Print the dataframe after modification
print(df)
输出:
正如我们在输出中看到的,Dataframe.transform()功能已成功将每个事件的门票费用增加了1000。