Python Pandas: 从销售数据集提取订单年月

本文将介绍如何使用 Python Pandas 库,从销售数据集 '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())

代码说明

  1. 导入 Pandas 库: import pandas as pd
  2. 读取数据集: 使用 pd.read_excel() 函数读取 'Online Retail.xlsx' 文件,并将其存储在名为 df 的 DataFrame 中。
  3. 将订单日期转换为日期类型: 使用 pd.to_datetime() 函数将 'InvoiceDate' 列转换为日期类型。
  4. 新建 '年月' 属性列: 使用 apply() 函数和 strftime() 方法,将 'InvoiceDate' 列中的每个日期转换为 '年月' 格式,并将其存储在名为 'YearMonth' 的新列中。
  5. 查看转换后的数据集: 使用 print(df.head()) 打印转换后的数据集前五行,以查看结果。

运行结果

运行代码后,输出的数据集中会多出一列名为 'YearMonth' 的属性列,其中每个订单的日期都被转换成了 '年月' 格式。

总结

本文介绍了如何使用 Python Pandas 库从销售数据集提取订单年月,并将其作为新的属性列添加到数据集中。您可以根据需要修改代码示例以适应不同的数据集和需求。

Python Pandas: 从销售数据集提取订单年月