python - Pandas ,在 groupby 之后创建列

标签 python pandas group-by multiple-columns

关于 Pandas DataFrame 'test_df':

 id_customer   id_order   product_name
    3             78        product1
    3             79        product2
    3             80        product3
    7             100       product4
    9             109       product5

在 'id_customer' 上进行 groupby 之后如何获得:

 id_customer order_1     order_2   product_name_1   product_name_2
    3          78           79           product1         product2
    7          100                       product4      
    9          109                       product5

目标是检索 2 和 groupby 之后匹配每个 'id_customer' 的行数之间的最小值,然后,如果可能的话,填写以上所有字段。

我开始了

def order_to_col(my_dataframe_df,my_list):
  for num in range(0,min(len(my_list),2)):
    my_dataframe_df['order_'+str(num)] = my_list[num]

test_df = test_df.groupby('id_customer').apply(lambda x: order_to_col(test_df,list(x.id_order)))

但我确定这不是好方法

最佳答案

注意:我建议使用 head 而不是使用多列:

In [11]: g = df.groupby('id_customer')

In [12]: g.head(2)
Out[12]:
   id_customer  id_order product_name
0            3        78     product1
1            3        79     product2
3            7       100     product4
4            9       109     product5

您可以使用 nth 组合第 0 和第 1,然后连接这些:

In [21]: g = df.groupby('id_customer')

In [22]: g[['id_order', 'product_name']].nth(0)
Out[22]:
             id_order product_name
id_customer
3                  78     product1
7                 100     product4
9                 109     product5

In [23]: g[['id_order', 'product_name']].nth(1)
Out[23]:
             id_order product_name
id_customer
3                  79     product2

In [24]: a = g[['id_order', 'product_name']].nth(0)
         b = g[['id_order', 'product_name']].nth(1)

In [25]: pd.concat([a, b], axis=1)
Out[25]:
             id_order product_name  id_order product_name
id_customer
3                  78     product1        79     product2
7                 100     product4       NaN          NaN
9                 109     product5       NaN          NaN

关于python - Pandas ,在 groupby 之后创建列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28438931/

相关文章:

python - 将 Twitter 时间转换为特定格式的日期时间,以统计一天中推文的频率

php - 根据 MA​​X 值和 GROUP BY 选择整行

python - 通过 shapefile 切割 NetCDF 文件

python - 将 datetime64 列拆分为 pandas 数据框中的日期和时间列

Python:永不消亡的函数

python - 通过列索引获取值,其中行是特定值

MySQL Group By 查找唯一组合

mysql - 使用 MySQL Group By 查询查找组中第二个项目的 ID

python - 如何延迟 Python 中脚本的执行?

python - 如何解析可变长度分隔文件中的数据?