【问题标题】:Getting value from groupby matrix从 groupby 矩阵中获取价值
【发布时间】:2018-01-03 19:50:12
【问题描述】:

我目前有一个如下所示的数据集。

DateTime, CustomerID, 2, 3, Product Subclass, ProductID, 6, 7, 8
2001-01-08 00:00:00;01217544  ;E ;E ;530112;4710094020568;1;51;66
2001-01-08 00:00:00;00102292  ;D ;F ;560102;4710032502811;1;115;128
2001-01-08 00:00:00;01443141  ;C ;E ;500538;2250078000251;1;69;78
2001-01-08 00:00:00;01439274  ;J ;E ;100401;4710043001211;1;409;450
2001-01-08 00:00:00;01724790  ;D ;F ;100202;4710047512065;1;15;18
2001-01-08 00:00:00;02013275  ;J ;E ;110217;4710892632017;2;370;398

我已将此数据拆分为更小的矩阵,每个日期和客户一个矩阵。我想从每个矩阵中提取 productID 并为每个客户的每一天创建一个交易数据集,其中包含每笔交易的 productID 行。

但是,我目前无法从较小的矩阵中获取 productID。我可以使用 groupby 函数拆分数据。但是,这会产生带有文本的 1x1 块,我似乎无法从中检索 ProductID。如何从我创建的组中获取 ProductID,以便我可以将它们放在一个列中的一个新数组中?

import numpy as np
import pandas as pd

'''DateTime, CustomerID, Product Subclass, ProductID'''
D01 = pd.read_csv('Data/D01.txt', sep=';', header=0, names=['DateTime','CustomerID','ProductSubclass', 'ProductID'], usecols=(0,1,4,5))
groupedData = np.asmatrix(D01.groupby(['DateTime','CustomerID']))

print np.asmatrix(groupedData)

我当前的一笔交易输出

[('2001-01-31 00:00:00', 2174006)
                     DateTime  CustomerID  ProductSubclass      ProductID
214244  2001-01-31 00:00:00     2174006           100208  4710144202227
214468  2001-01-31 00:00:00     2174006           500111  4718433614799
214819  2001-01-31 00:00:00     2174006           100110  4901550332077
215420  2001-01-31 00:00:00     2174006           500303  4710367807421]]

期望的输出

 ...   
(4710144202227, 4718433614799, 4901550332077, 4710367807421)
 ...

【问题讨论】:

  • 为什么你在同一件事上使用了两次np.asmatrix()

标签: python pandas validation dataframe pandas-groupby


【解决方案1】:

这是你要找的吗?

# make data
df = pd.DataFrame({
    'datetime' : [pd.to_datetime('2001-01-08')] * 6,
    'customerID' : ['01217544', '00102292', '01443141', '01439274', '01724790', '02013275'],
    2 : ['E', 'D', 'C', 'J', 'D', 'D'],
    3 : ['E', 'F', 'E', 'E', 'F', 'E'],
    'product_subclass' : [530112, 560102, 500538, 100401, 100202, 110217],
    'productID' : [4710094020568, 4710032502811, 2250078000251, 4710043001211, 4710047512065, 4710892632017],
    6 : [1, 1, 1, 1, 1, 2],
    7 : [51, 115, 69, 409, 15, 370],
    8 : [66, 128, 78, 450, 18, 398]
})

# set index as 'datetime' and 'customerID'
df = df.set_index([
    'datetime',
    'customerID'
]).sort_index()

# cross section on 2001-01-08 and customerID = 00102292
df.xs(['20010108', '00102292'])['productID']

【讨论】:

  • 不完全是,但是您的索引解决方案帮助我更好地理解了 DataFrames!我只需要 np.asmatrix(groupedData.item(1))[1,3]
猜你喜欢
  • 1970-01-01
  • 2019-10-09
  • 2014-04-11
  • 1970-01-01
  • 2020-06-12
  • 1970-01-01
  • 1970-01-01
  • 2012-08-28
  • 2021-08-31
相关资源
最近更新 更多