繁体   English   中英

如何在 pandas 中获得每月第一天和最后一天的价值?

[英]How do i get the first and last day value per month in pandas?

所以我有一个巨大的 CSV ,我想从每个月的第一天和最后一天获取数据(来自一个特定的列)。 我考虑过使用 pandas ,因为我已经使用它了一点。 到目前为止我所拥有的:

import logging
import pandas as pd
import os
import glob

# Define Logger
logging.basicConfig(level=logging.INFO, format=' %(asctime)s - %(levelname)s - %(message)s')
logging.info('Start of program')

# set working directory
os.chdir("Path to CSVs")

extension = 'csv'
all_filenames = [i for i in glob.glob('*.{}'.format(extension))]

combined_csv = pd.concat([pd.read_csv(f, sep=';') for f in all_filenames])
logging.info('Combining all CSVs into one....')
combined_csv['Timestamp'] = pd.to_datetime(combined_csv.Timestamp)
logging.info('Transforming Timestamps into datetime....')
res = combined_csv.groupby(combined_csv.index.date).apply(lambda x: x.iloc[[0, -1]])
res.index = res.index.droplevel(0)

print(res)

因为我是 Pandas 的初学者,所以我不知道如何继续前进。 我得到一个错误。 我有错误的数据类型吗?

AttributeError: 'Int64Index' object has no attribute 'date'

您可以按date排序,然后尝试:

df.sort_values(by='date', inplace=True)
df['month'] = df.date.dt.to_period('M')
df.groupby(['month'])['column'].agg(['first', 'last'])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM