【问题标题】:Sorting data by time column python按时间列python对数据进行排序
【发布时间】:2021-09-29 14:57:59
【问题描述】:

我有这个数据集,格式如下:

   time_col            val_col  value            
0   2021-04-28 12:10:00 10       Students   
1   2021-04-28 12:20:00 20       Students
2   2021-04-28 12:30:00 20       Students
3   2021-04-28 12:40:00 35       Students
4   2021-04-28 12:50:00 35       Students
5   2021-04-28 12:10:00 100      Noise
6   2021-04-28 12:20:00 130      Noise
7   2021-04-28 12:30:00 155      Noise
8   2021-04-28 12:40:00 160      Noise
9   2021-04-28 12:50:00 175      Noise

时间是重复的,所以我希望输出看起来像:

   time_col            Students  Noise            
0   2021-04-28 12:10:00 10       100    
1   2021-04-28 12:20:00 20       130
2   2021-04-28 12:30:00 20       155
3   2021-04-28 12:40:00 35       160
4   2021-04-28 12:50:00 35       175

请告诉我怎么做。

这是我制作第一个 df 的方式:

time_col = [np.datetime64('2021-04-28T12:10:00'), np.datetime64('2021-04-28T12:20:00'), np.datetime64('2021-04-28T12:30:00'), np.datetime64('2021-04-28T12:40:00'), np.datetime64('2021-04-28T12:50:00'),
           np.datetime64('2021-04-28T12:10:00'), np.datetime64('2021-04-28T12:30:00'), np.datetime64('2021-04-28T12:30:00'), np.datetime64('2021-04-28T12:40:00'), np.datetime64('2021-04-28T12:50:00')]
val_col = [10,20,20,35,35, 100,135,155,160,175]
value = ["Students", "Students", "Students", "Students", "Students", "Noise", "Noise", "Noise", "Noise", "Noise"]
df_1 = pd.DataFrame([time_col, val_col, value])
df_2 = pd.DataFrame.transpose(df_1)
df_2.columns = ["time_col", "val_col", "value"]

如您所见,我是 python 新手,我知道这不是创建 df 的最佳方式

【问题讨论】:

标签: python pandas dataframe numpy


【解决方案1】:

看看pivot_table:

# make the val_col values floats instead of objects
df_2.val_col = df_2.val_col.astype(float)

# pivot the df and aggregate duplicate indeces with the mean function
df_2.pivot_table(columns="value", values="val_col", index="time_col")

返回数据帧:

value                Noise  Students
time_col                            
2021-04-28 12:10:00  100.0      10.0
2021-04-28 12:20:00    NaN      20.0
2021-04-28 12:30:00  145.0      20.0
2021-04-28 12:40:00  160.0      35.0
2021-04-28 12:50:00  175.0      35.0

您可以将aggfunc 传递给pivot_table(例如mean)来处理同一时间段的多个测量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-05
    • 2010-11-20
    • 2011-10-13
    • 2011-10-31
    • 1970-01-01
    • 2020-02-03
    相关资源
    最近更新 更多