努力使用 python 代码按时间顺序对每月数据平均值进行排序
Struggling with python code to sort monthly data mean in chronological order
我是 Python 的新用户,在使用 Pandas 将每日时间序列数据按正确顺序排序为每月数据时遇到问题。我有一个很大的每日数据集,例如片段:
Date Current_BP month year
0 1/7/1895 76883.020 7 1895
1 2/7/1895 31387.660 7 1895
2 3/7/1895 14113.330 7 1895
3 4/7/1895 7587.465 7 1895
4 5/7/1895 5222.271 7 1895
我想计算月平均值并使用此代码:
df=df.groupby(['year', 'month']).mean()
这给出了这样的数据:
year month Current_BP
1895 10 35154.870968
11 8511.711567
12 2190.365226
7 12342.392387
8 19052.299355
9 26362.408667
1896 1 2000.000000
10 10325.662645
11 16764.958900
12 2018.403677
我遇到的问题是,为了绘图,我需要按时间顺序排列的月度数据(即每年按 1-12 月排序)。
正如@Tim Roberts 所说,将列转换为整数:df['month'] = df['month'].astype(int)。否则,您的字符串排序顺序为 1、10、11 在 2 之前。
df = pd.DataFrame({'month': ['7', '7', '7', '10', '12', '1'],
'Current_BP': [1, 2, 3, 4, 5, 6]})
df['year'] = 1895
df2 = df.groupby(['year', 'month']).mean() # wrong order
df['month'] = df['month'].astype(int) # convert string to integer
df3 = df.groupby(['year', 'month']).mean()
print(df3)
# Current_BP
# year month
# 1895 1 6
# 7 2
# 10 4
# 12 5
我是 Python 的新用户,在使用 Pandas 将每日时间序列数据按正确顺序排序为每月数据时遇到问题。我有一个很大的每日数据集,例如片段:
Date Current_BP month year
0 1/7/1895 76883.020 7 1895
1 2/7/1895 31387.660 7 1895
2 3/7/1895 14113.330 7 1895
3 4/7/1895 7587.465 7 1895
4 5/7/1895 5222.271 7 1895
我想计算月平均值并使用此代码:
df=df.groupby(['year', 'month']).mean()
这给出了这样的数据:
year month Current_BP
1895 10 35154.870968
11 8511.711567
12 2190.365226
7 12342.392387
8 19052.299355
9 26362.408667
1896 1 2000.000000
10 10325.662645
11 16764.958900
12 2018.403677
我遇到的问题是,为了绘图,我需要按时间顺序排列的月度数据(即每年按 1-12 月排序)。
正如@Tim Roberts 所说,将列转换为整数:df['month'] = df['month'].astype(int)。否则,您的字符串排序顺序为 1、10、11 在 2 之前。
df = pd.DataFrame({'month': ['7', '7', '7', '10', '12', '1'],
'Current_BP': [1, 2, 3, 4, 5, 6]})
df['year'] = 1895
df2 = df.groupby(['year', 'month']).mean() # wrong order
df['month'] = df['month'].astype(int) # convert string to integer
df3 = df.groupby(['year', 'month']).mean()
print(df3)
# Current_BP
# year month
# 1895 1 6
# 7 2
# 10 4
# 12 5