【问题标题】:Creating a list of dataframes from a daraframe in python从python中的数据框创建数据框列表
【发布时间】:2019-08-12 18:05:18
【问题描述】:
df = 
    c1  c2
    ds  43
    ds  34
    ds  32
    foo 34
    foo 32

我想从df 创建数据帧列表,根据c1 列拆分并分配行号。

输出list 应该是这样的,我以后可以从中选择单个数据帧

out_list:

[[1]]
c1   c2  rownum
ds   43  1
ds   34  2
ds   32  3
[[2]]
c1   c2  rownum
foo  34  1
foo  32  2

R 中,我可以通过split 函数来做到这一点。我如何在 Python 中做到这一点?

示例 R 代码,

df %>% split(.$c1) %>% map(~mutate(., rownum= row_number()))

【问题讨论】:

    标签: python r pandas list


    【解决方案1】:

    首先在 groupby 上使用 cumcount 创建列 row nm。接下来,在 groupby 对象上使用 listcomp

    df['row nm'] = df.groupby('c1').cumcount().add(1)
    
    Out[157]:
        c1  c2  row nm
    0   ds  43       1
    1   ds  34       2
    2   ds  32       3
    3  foo  34       1
    4  foo  32       2
    
    gb_list = [g.reset_index(drop=True) for _, g in df.groupby('c1')]
    
    Out[176]:
    [   c1  c2  row nm
     0  ds  43       1
     1  ds  34       2
     2  ds  32       3,     c1  c2  row nm
     0  foo  34       1
     1  foo  32       2]
    
    In [177]: gb_list[0]
    Out[177]:
       c1  c2  row nm
    0  ds  43       1
    1  ds  34       2
    2  ds  32       3
    
    In [178]: gb_list[1]
    Out[178]:
        c1  c2  row nm
    0  foo  34       1
    1  foo  32       2
    

    【讨论】:

    • 很好,也许还包括reset_index 在该列表中?也可能groupby 调用可以被缓存,因此不需要调用两次?
    • 啊,我明白你的意思了。由于 OP 没有具体说明每个子数据帧的索引,所以我不想重置它。我同意df.groupby('c1') 可以分配给一个变量,并在以后使用该变量。但是,在性能上并没有什么不同,因为 groupby 是惰性运算符。
    • 你能告诉我reset_index 是做什么的吗?
    • @HarikrishnanBalachandran: reset_index 会将每个子数据帧索引重置为从0 开始的范围索引。查看当前gb_list[1] 第一列是3, 4。如果你链接reset_index,它将是0, 1
    • @HarikrishnanBalachandran:我添加了reset_index。检查我的更新
    【解决方案2】:

    使用字典,这使您可以灵活地以任何您想要的方式制作数据框

    d = {key: df.loc[value] for key, value in df.groupby("c1").groups.items()}
    d.values() #gives you the required output you want
    

    您还可以按照自己想要的方式格式化数据框

    for k,v in d.items():
        globals()['df_' + str(k)] = pd.DataFrame(v)   #here globals() is used to create and access df name dynamically
        globals()['df_' + str(k)]['rank'] = globals()['df_' + str(k)].groupby('c1').cumcount().add(1)
        globals()['df_' + str(k)].reset_index(drop=True, inplace=True)
    

    您的数据框是 df_dsdf_foo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-07
      • 2021-12-22
      • 2017-08-27
      • 1970-01-01
      • 1970-01-01
      • 2016-02-29
      相关资源
      最近更新 更多