python中transform用法_Python Pandas Series.transform()用法及代码示例

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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值