我想知道如何按月对数据进行分组,以便每月查看数据。我该怎么做?
例如,将1月份记录在自己的数据帧中的所有数据分配给1月份进行分析,等等。
这是我当前的数据帧:
WC_Humidity[%] WC_Htgsetp[C] WC_Clgsetp[C] Date Time
0 55.553640 18 26 2005-01-01 00:10
1 54.204342 18 26 2005-01-01 00:20
2 51.896272 18 26 2005-01-01 00:30
3 49.007770 18 26 2005-01-01 00:40
4 45.825810 18 26 2005-01-01 00:50
我们非常感谢您的帮助。
试试这个:
df1['Date'].to_numpy().astype('datetime64[M]')
您可以使用以下代码转换您的列。
df1['Date'] = pd.to_datetime(df["Date"].dt.strftime('%d-%m-%Y'))
你可以参考官方文件了解为什么第一天不起作用。https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html
如果你有像2005-01-01
这样的字符串,那么你可以得到
df['year-month'] = df['Date'].str[:7]
以后你可以使用
df.groupby('year-month')
最小工作代码。
我更改了日期以在数据中包含不同的月份。
我只使用io
来模拟内存中的文件。
text = '''WC_Humidity[%],WC_Htgsetp[C],WC_Clgsetp[C],Date,Time
55.553640,18,26,2005-01-01,00:10
54.204342,18,26,2005-01-01,00:20
51.896272,18,26,2005-02-01,00:30
49.007770,18,26,2005-02-01,00:40
45.825810,18,26,2005-03-01,00:50
'''
import pandas as pd
import io
df = pd.read_csv(io.StringIO(text))
df['year-month'] = df['Date'].str[:7]
print(df)
for value, group in df.groupby('year-month'):
print()
print('---', value, '---')
print(group)
print()
print('average WC_Humidity[%]:', group['WC_Humidity[%]'].mean())
结果:
WC_Humidity[%] WC_Htgsetp[C] WC_Clgsetp[C] Date Time year-month
0 55.553640 18 26 2005-01-01 00:10 2005-01
1 54.204342 18 26 2005-01-01 00:20 2005-01
2 51.896272 18 26 2005-02-01 00:30 2005-02
3 49.007770 18 26 2005-02-01 00:40 2005-02
4 45.825810 18 26 2005-03-01 00:50 2005-03
--- 2005-01 ---
WC_Humidity[%] WC_Htgsetp[C] WC_Clgsetp[C] Date Time year-month
0 55.553640 18 26 2005-01-01 00:10 2005-01
1 54.204342 18 26 2005-01-01 00:20 2005-01
average WC_Humidity[%]: 54.878991
--- 2005-02 ---
WC_Humidity[%] WC_Htgsetp[C] WC_Clgsetp[C] Date Time year-month
2 51.896272 18 26 2005-02-01 00:30 2005-02
3 49.007770 18 26 2005-02-01 00:40 2005-02
average WC_Humidity[%]: 50.452021
--- 2005-03 ---
WC_Humidity[%] WC_Htgsetp[C] WC_Clgsetp[C] Date Time year-month
4 45.82581 18 26 2005-03-01 00:50 2005-03
average WC_Humidity[%]: 45.82581
如果你有对象datetime
,那么你可以进行
df['year-month'] = df['Date'].dt.strftime('%Y-%m')
其余的是相同的
text = '''WC_Humidity[%],WC_Htgsetp[C],WC_Clgsetp[C],Date,Time
55.553640,18,26,2005-01-01,00:10
54.204342,18,26,2005-01-01,00:20
51.896272,18,26,2005-02-01,00:30
49.007770,18,26,2005-02-01,00:40
45.825810,18,26,2005-03-01,00:50
'''
import pandas as pd
import io
df = pd.read_csv(io.StringIO(text))
# create datetime objects
df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d')
df['year-month'] = df['Date'].dt.strftime('%Y-%m')
print(df)
for value, group in df.groupby('year-month'):
print()
print('---', value, '---')
print(group)
print()
print('average WC_Humidity[%]:', group['WC_Humidity[%]'].mean())
如果列的格式是2021-01-29,30-12-2024,那么在上面的行之前应该处理它并相应地解析它。
df1['Date'] = pd.to_datetime(df1['Date'])
现在,您可以使用此代码将日期列转换为所需的方式。
df1['Date'] = df['Date1'].dt.strftime('%d/%m/%Y')
这应该能得到你想要的。