簡體   English   中英

如何使用 Python Dataframe 根據日期計算值並存儲在特定列中?

[英]How to calculate values and stored in a particular column based on date using Python Dataframe?

我有一個包含日期、產品、數量和數字列的 Dataframe。基於此 dataframe,我想創建一個新的 Dataframe 和 A1FBZ,其中包含月、年、產品中相應的月、年、測量值列。在新的 dataframe 中,而不是所有日期。

下圖顯示了兩個表:

第一的: 在此處輸入圖像描述

我想要這樣的表:

第二: 在此處輸入圖像描述

Dataframe:

import pandas as pd

data = {'Date': ['01-01-2021', '02-01-2021', '03-01-2021', '01-02-2021', '02-02-2021', '03-02-2021'],
    'product': ['Apple', 'Apple', 'Apple', 'Apple', 'Apple', 'Apple'],
    'quantity': [1,2,3,4,5,6],
    'numbers': [1,2,3,4,5,6]}
df = pd.DataFrame(data)
print(df)

誰能幫我解決這個問題?

首先我們需要轉換年、月、日、小時

# change the invoice_date format - String to Timestamp format
df['InvoiceDate'] = pd.to_datetime(df.InvoiceDate, format='%m/%d/%Y %H:%M')
df.insert(loc=2, column='Year_Month', value=df['InvoiceDate'].map(lambda x: 100*x.year + x.month))

df.insert(loc=3, column='Month', value=df.InvoiceDate.dt.month)

# +1 to make Monday=1.....until Sunday=7

df.insert(loc=4, column='Day', value=(df.InvoiceDate.dt.dayofweek)+1)

df.insert(loc=5, column='Hour', value=df.InvoiceDate.dt.hour)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM