是否有 pandas 或 numpy 函数可以通过查看月份(MM)是否以 1 的格式递增来识别新月份是否出现 YYYY-MM-DD-TTTT
。因此,在下面的示例中,我试图查看一个函数是否可以指示日期从 10 月 2015-10-31 23:59:00
到 12 月 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'
预期输出
At the 11th index the Month changes
最佳答案
由于您可能会想要确定月份再次更改的位置,因此我提供了针对多个月份更改的解决方案。这里使用pandas的.diff()
,引用:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.diff.html
# 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')
关于python - Pandas Python 中的数据框读取和日期格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66539657/