【问题标题】:How to partition pandas data frame according to time stamp?如何根据时间戳对熊猫数据框进行分区?
【发布时间】:2017-11-05 16:05:33
【问题描述】:

我有一个熊猫数据框列时间戳,ID,纬度,经度。这个数据框大约有一个月的时间。如何绘制不同访问位置的数量与时间(每天或每周)?

Time Stamp              Id  Latitude    Longitude
08/10/2016 15:22:51:700 1      23        50
08/10/2016 16:28:08:026 1      23        50
08/10/2016 16:28:09:026 1      12        45
08/10/2016 19:00:08:026 2      23        50
08/10/2016 20:28:08:026 1      23        50
08/10/2016 19:00:08:000 2      23        50
09/10/2016 01:02:33:123 2      23        50
09/10/2016 06:15:08:500 1      23        50
09/10/2016 10:01:07:022 3      28        88

【问题讨论】:

  • 请获取该数据,将其复制并粘贴到您的问题中。希望这不是难做到。
  • 嗨,COLDSPEED,你能帮我解决我的问题吗?我已编辑。实际上,我每天都需要每个用户的 No of Distinct Position。
  • 您已经接受了一个答案...您是说这没有帮助吗?
  • 它有帮助,但我也需要它。因为我的老师修改了问题。我将我的新问题发布为新问题
  • 听起来你应该自己做作业,伙计!

标签: python pandas dataframe


【解决方案1】:

我相信你需要:

首先由to_datetime 创建日期时间Series - times 已被删除,所以得到datetimes 没有时间。 (感谢cᴏʟᴅsᴘᴇᴇᴅ 的想法)

然后groupby 得到nunique,最后plot

days = pd.to_datetime(df['Time Stamp'].str.split().str[0])

s1 = df['Id'].groupby(days).nunique()
print (s1)
Time Stamp
2016-08-10    2
2016-09-10    3
Name: Id, dtype: int64


s1.plot()

几周转换为weeks:

weeks = days.dt.week

s2 = df['Id'].groupby(weeks).nunique()
print (s2)
Time Stamp
32    2
36    3
Name: Id, dtype: int64

s2.plot()

所有日期的另一种方法是resample

df['Days'] = pd.to_datetime(df['Time Stamp'].str.split().str[0])

s2 = df.resample('D', on='Days')['Id'].nunique()

print (s2)
Days
2016-08-10    2
2016-08-11    0
2016-08-12    0
2016-08-13    0
2016-08-14    0
2016-08-15    0
2016-08-16    0
2016-08-17    0
2016-08-18    0
2016-08-19    0
2016-08-20    0
2016-08-21    0
2016-08-22    0
2016-08-23    0
2016-08-24    0
2016-08-25    0
2016-08-26    0
2016-08-27    0
2016-08-28    0
2016-08-29    0
2016-08-30    0
2016-08-31    0
2016-09-01    0
2016-09-02    0
2016-09-03    0
2016-09-04    0
2016-09-05    0
2016-09-06    0
2016-09-07    0
2016-09-08    0
2016-09-09    0
2016-09-10    3
Freq: D, Name: Id, dtype: int64

s2.plot()

几周:

s2 = df.resample('W', on='Days')['Id'].nunique()
print (s2)
Days
2016-08-14    2
2016-08-21    0
2016-08-28    0
2016-09-04    0
2016-09-11    3
Freq: W-SUN, Name: Id, dtype: int64


s2.plot()

【讨论】:

  • pd.to_datetime(df['Time stamp']) 不起作用 - 看看格式,很奇怪。
  • 使用df['Time Stamp'] = pd.to_datetime(df['Time Stamp'].str.split().str[0]) ...因为你只需要一周,你可以摆脱时间。
  • 第一行有效。但是第二行说错误。 df4(['Weeks']) = df4['Start_Time'].dt.week ^ SyntaxError: can't assign to function call
  • 对不起,我的错字。删除 () 喜欢 df4['Weeks']
  • 谢谢!!但实际上我需要访问不同的位置(纬度,经度)VS时间..不是ID
猜你喜欢
  • 1970-01-01
  • 2022-01-25
  • 2021-11-02
  • 1970-01-01
  • 2015-10-30
  • 2014-04-23
  • 1970-01-01
  • 2023-02-13
  • 2015-05-11
相关资源
最近更新 更多