【问题标题】:Group Dataframe by day using pandas使用熊猫按天分组数据框
【发布时间】:2018-12-11 14:03:42
【问题描述】:

我有一个表单中的数据框:

      user                    accuracy  latitude  longitude      timestamp
0   5573502c150000c10136e51b    29.942 -8.658122 -45.700106  1434127670836
1   5573502c150000c10136e51b    30.000 -8.658068 -45.700127  1434127730889
2   5573502c150000c10136e51b    30.000 -8.658068 -45.700127  1434127790911
3   5573502c150000c10136e51b    30.000 -8.658057 -45.700123  1434127858915
4   5573502c150000c10136e51b    39.000 -8.658072 -45.700108  1434127918948
5   5573502c150000c10136e51b    31.876 -8.658100 -45.700107  1434128021062
6   5573502c150000c10136e51b    30.048 -8.658116 -45.700140  1434128151467
7   5573502c150000c10136e51b    30.473 -8.658118 -45.700097  1434128277097
8   5573502c150000c10136e51b    55.500 -6.658087 -45.700138  1434140105618
9   5573502c150000c10136e51b    55.500 -6.658087 -45.700138  1434140165685
10  5573502c150000c10136e51b    30.000 -6.658057 -45.700130  1434140225898
11  5573502c150000c10136e51b    30.000 -6.658057 -45.700130  1434140285952
12  5573502c150000c10136e51b    30.000 -7.658084 -45.700113  1434140346166
13  5573502c150000c10136e51b    36.000 -7.658051 -45.700138  1434140406214
14  5573502c150000c10136e51b    36.000 -5.658051 -45.700138  1434140466240
15  5573502c150000c10136e51b    32.908 -5.658091 -45.700097  1434140526278
16  5573502c150000c10136e51b    32.908 -5.658091 -45.700097  1434140586325
17  5573502c150000c10136e51b    34.009 -5.658075 -45.700119  1434140646363
18  5573502c150000c10136e51b    30.000 -5.658058 -45.700118  1434140706409
19  5573502c150000c10136e51b    30.000 -5.658058 -45.700118  1434140766455

我想按天对数据框进行分组,然后将每天的记录附加到不同的列表中。

所以我有:

DFList = [group[1] for group in df.groupby(df.index.day)]
print DFList

但我得到一个错误:

AttributeError: 'RangeIndex' 对象没有属性 'day'

谁能知道如何解决这个问题?

【问题讨论】:

  • df.index.day ??但索引不是 datetime na 类型。
  • 您的 DataFrame 的 Index 是默认的整数范围索引。您需要将 timestamp 列转换为 DatetimeIndex 并从那里开始,例如 df.set_index(pd.to_datetime(df['timestamp']))

标签: python pandas python-2.7 dataframe


【解决方案1】:

我认为您首先需要to_datetimeunit='ms',然后再转换为Series.dt.day

df['day'] = pd.to_datetime(df['timestamp'], unit='ms').dt.day

dfs = [x for i, x in df.groupby('day')]

或者如果需要DatetimeIndex:

df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
df = df.set_index('timestamp')
dfs = [x for i, x in df.groupby(df.index.day)]
print (dfs)

如果需要相同格式的时间戳列:

day = pd.to_datetime(df['timestamp'], unit='ms').dt.day

dfs = [x for i, x in df.groupby(day)]

【讨论】:

  • 谢谢@jezrael。你能提供如何将每天的记录添加到列表中的代码吗?
  • @Antonis - 哪些列需要附加到列表中?
  • 我使用您提供的第一段代码。我想添加除“天”以外的所有元素。
  • @Antonis - 使用第二个 Or if need DatetimeIndex: :)
  • @Antonis - 如果需要嵌套列表dfs = [x.values.tolist() for i, x in df.groupby(df.index.day)]
猜你喜欢
  • 1970-01-01
  • 2013-02-28
  • 2019-04-13
  • 2019-10-14
  • 2017-07-08
  • 2021-08-11
  • 2018-07-19
  • 2019-05-15
  • 2017-10-17
相关资源
最近更新 更多