[英]Dataframe reading and formatting with dates in Pandas Python
是否有一個 pandas 或 numpy YYYY-MM-DD-TTTT
通過查看月份(MM)是否增加了格式來識別新月份是否出現。 因此,在下面的示例中,我試圖查看 function 是否可以指示日期從十月2015-10-31 23:59:00
到十二月2015-11-01 00:00:00
的哪個索引。
代碼
import pandas as pd
#Getting the input from a csv file
data= 'input.csv'
#Reverses all the table data values
data1 = data.iloc[::-1].reset_index(drop=True)
#Getting The date column
Date = np.array(data1['Date'])
部分日期,第 11 個索引是從 10 月到 11 月
['2015-10-31 23:50:00' '2015-10-31 23:51:00' '2015-10-31 23:52:00'
'2015-10-31 23:53:00' '2015-10-31 23:54:00' '2015-10-31 23:55:00'
'2015-10-31 23:56:00' '2015-10-31 23:57:00' '2015-10-31 23:58:00'
'2015-10-31 23:59:00' '2015-11-01 00:00:00' '2015-11-01 00:01:00'
'2015-11-01 00:02:00' '2015-11-01 00:03:00' '2015-11-01 00:04:00'
預計 Output
At the 11th index the Month changes
因為您可能會達到想要再次確定月份變化的地步,所以我提供了一個針對多個月份變化的解決方案。 這里使用 pandas 的.diff()
,參考: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.diff.ZFC35FDC70D5FC69D23EZ883A
# first convert strings to datetime
data1['Date'] = pd.to_datetime(data1['Date'])
month_changes = data1.loc[np.where(data1['Date'].dt.month.diff().gt(0))].index.tolist()
for month_change in month_changes:
print(f'At the {month_change + 1}th index the month changes')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.