【问题标题】:Subset a Python 3.x dataframe based on a list基于列表对 Python 3.x 数据框进行子集化
【发布时间】:2018-03-31 03:21:47
【问题描述】:

我有一个数据框 df 和一个列表 in_list,其中包含多个用户 ID。我想根据in_list 的用户ID 创建多个数据框。

这里是列表:

in_list = 
[4638472273,
 1559410755,
 4931532174,
 2419930464,
 1884182865,
 3688089071,
 4555003213,
 2068627935,
 2894365987,
 8549533077]

这里是代码:

i = 0
while i < len(in_list):
    user_index[i] = df[(df.In == in_list[i])] 
    i += 1

当我执行上述代码时,我收到此错误消息ValueError: Cannot set a frame with no defined index and a value that cannot be converted to a Series

我想用数据帧的子集df创建几个名为user_index0user_index1user_index2 等的数据帧,但我遇到了这个错误。

【问题讨论】:

  • 你能分享你需要的输出数据框吗?什么是 user_index?
  • user_index[i] = df[(df.In == in_list[i])] ->>>> user_index[i] 将导致 user_index 是一个字典并且 i 的值作为键。这是故意的吗?

标签: python python-3.x list pandas


【解决方案1】:

您可以使用isin 过滤您的数据框以首先匹配“in_list”,然后将groupby“in”和append 组的结果匹配到“user_index”列表:

user_index = []
for _,g in df[df['in'].isin(in_list)].groupby('in'):
    user_index.append(g)

【讨论】:

    【解决方案2】:

    您可以使用列表推导轻松完成此操作:

    df_list = [df[df.In == i] for i in in_list]
    

    那么,如果你想要一本字典,就这样做:

    df_dict = dict(zip(range(0,len(in_list)), df_list))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-07
      • 2013-08-15
      • 2021-04-25
      相关资源
      最近更新 更多