python - Pandas Python 中的数据框读取和日期格式化

标签 python pandas numpy date datetime

是否有 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/

相关文章:

python | pydub : how to load wav sample into pydub from np. 数组而不是 wav 文件?

python - 在 Python 中使用 Tkinter 时程序挂起

Python,在shell中隐藏密码

python pandas read_csv如何加快处理时间戳

python - 当函数应用于行时, Pandas 的 .groupby 函数出现奇怪的问题

python - 使用字典存储数据的更干净的方法

python - 使用索引偏移堆叠数组的简单方法

python - 使用 ctypes 在 python 中调用 c 函数

python - 通过 pandas 数据框中单独的计数列聚合重复的起点和目标值来创建新的数据框

python - numpy中任意函数的按行广播