Python,dataframes:如何为python数据框中键重复的每个值创建字典/系列/数据帧?

时间:2018-01-18 12:12:31

标签: python pandas dataframe

我创建的数据帧如下:

+---------+--------+-----+-------------+
| VideoID |   long | lat | viewerCount |
+---------+--------+-----+-------------+
| 123     |   -1.1 | 1.1 |     25      |
+---------+--------+-----+-------------+
| 123     |   -1.1 | 1.1 |     20      |
+---------+--------+-----+-------------+

videoIDs是Facebook上视频直播的IDs。而viewerCount是观看者的数量。 我每隔30秒就添加一次刷新值。 videoIDs大部分都是重复的,但viewerCount会发生变化。 所以我想要的是存储新的viewerCount但不存在视频ID的重复 (即:viewerCount现在不是单列,但可以是字典或系列)。像这样的东西: the table showing the format i expect (to clear the point)

1 个答案:

答案 0 :(得分:0)

所以,在我回答你的问题之前,我有一个评论。除非您正在处理“大数据”(内存中的连接操作会占用存储空间和可能的更新成本),建议您将表拆分为两个。
- 第一个将包含视频详细信息Video_id*, longitude, latitude, location
- 第二个表格将包含Video_id, refreshes and Views

话虽如此,有几种选择可以达到最终的表现形式。我将使用自己的解决方案是将Viewers_count存储为列表。列表将是有益的,因为可以将Num_refresh全部删除,因为它可以从元素索引重新计算。 在这种情况下,使用dicts将是不必要的昂贵和复杂,但我也将添加语法。

df = pd.DataFrame({'id': list("aabb"), 
                   'location': list("xxyy"),
                   'views': [3, 4, 1, 2]})
#   id location  views
# 0  a        x      3
# 1  a        x      4
# 2  b        y      1
# 3  b        y      2

grouped_df = (df
              .groupby(["id", "location"])["views"] # Create a group for each [id, location] and select view
              .apply(np.hstack)                     # Transform the grouped views to a list
            # .apply(lambda x: dict(zip(range(len(x)), x))) # Dict
              .reset_index())                       # Move id and location to regular columns

#   id location   views
# 0  a        x  [3, 4]
# 1  b        y  [1, 2]

更新

您在评论中提到了迭代期间嵌套列表的问题。您可以将list替换为np.hstack

# Second iterations 
iter_2 = pd.DataFrame({'id': list("aabb"), 
                       'location': list("xxyy"),
                       'views': [30, 40, 10, 20]})

grouped_df = (grouped_df
              .append(iter_2)                       # Add the rows of the new dataframe to the grouped_df
              .groupby(["id", "location"])["views"]
              .apply(np.hstack)
              .reset_index())

#   id location           views
# 0  a        x  [3, 4, 30, 40]
# 1  b        y  [1, 2, 10, 20]