对销售数据集online retail将订单日期转换出年月、并作为新的属性列给出代码
以下是对销售数据集online retail,将订单日期转换出“年月”并作为新的属性列的代码:
import pandas as pd
# 读取数据集
df = pd.read_excel('Online Retail.xlsx')
# 将订单日期转换为日期类型
df['InvoiceDate'] = pd.to_datetime(df['InvoiceDate'])
# 新建“年月”属性列
df['YearMonth'] = df['InvoiceDate'].apply(lambda x: x.strftime('%Y-%m'))
# 查看转换后的数据集
print(df.head())
运行代码后,输出的数据集中会多出一列名为“YearMonth”的属性列,其中每个订单的日期都被转换成了“年月”格式。
原文地址: https://www.cveoy.top/t/topic/gIau 著作权归作者所有。请勿转载和采集!