繁体   English   中英

groupby 在包含字节数组 object 的列上使用 Pandas Dataframe

[英]groupby on column which contain bytearray object using Pandas Dataframe

我有 pandas dataframe 并想对客户 ID 进行 groupby

 df['rank_col'] = df.groupby('PSEUDO_CUSTOMER_ID')['DB_CREATED_DT'].rank(method='first')

现在问题是 pseudo_customer_ID 看起来像这样

 [138, 76, 16, 9, 86, 71, 5, 85, 117, 237, 97, 212, 13, 157, 185, 150, 207, 97, 85, 165] 

下面是我对伪客户 ID 进行价值计数时的快照,

在此处输入图像描述

我检查我得到的单个值低于值

在此处输入图像描述

注意:我想对 pseudo_customer_ID 进行 groupby 并按 DB_CREATED_DT 列进行排名

使用bytes function 转换您的bytearray以允许分组(并获取可散列类型):

演示:

df['PSEUDO_CUSTOMER_ID_BYTES'] = df['PSEUDO_CUSTOMER_ID'].apply(bytes)
print(df)

# Output:
                                  PSEUDO_CUSTOMER_ID                           PSEUDO_CUSTOMER_ID_BYTES
0  [138, 76, 16, 9, 86, 71, 5, 85, 117, 237, 97, ...  b'\x8aL\x10\tVG\x05Uu\xeda\xd4\r\x9d\xb9\x96\x...

PSEUDO_CUSTOMER_ID

>>> list(df.groupby('PSEUDO_CUSTOMER_ID'))
...
TypeError: unhashable type: 'bytearray'

PSEUDO_CUSTOMER_ID_BYTES

>>> list(df.groupby('PSEUDO_CUSTOMER_ID_BYTES'))

[(b'\x8aL\x10\tVG\x05Uu\xeda\xd4\r\x9d\xb9\x96\xcfaU\xa5',
                                    PSEUDO_CUSTOMER_ID                           PSEUDO_CUSTOMER_ID_BYTES
  0  [138, 76, 16, 9, 86, 71, 5, 85, 117, 237, 97, ...  b'\x8aL\x10\tVG\x05Uu\xeda\xd4\r\x9d\xb9\x96\x...)]

重要的

如果您确定原始编码,则可以使用str.decode来获取str而不是bytes字符串。 这里似乎是latin-1

df['PSEUDO_CUSTOMER_ID_STR'] = df['PSEUDO_CUSTOMER_ID'].decode('latin1'))
print(df.loc[0])

# Output:
PSEUDO_CUSTOMER_ID          [138, 76, 16, 9, 86, 71, 5, 85, 117, 237, 97, ...
PSEUDO_CUSTOMER_ID_BYTES    b'\x8aL\x10\tVG\x05Uu\xeda\xd4\r\x9d\xb9\x96\x...
PSEUDO_CUSTOMER_ID_STR                                 L\tVGUuíaÔ\rÏaU¥
Name: 0, dtype: object

演示:

>>> list(df.groupby('PSEUDO_CUSTOMER_ID_STR'))

[('\x8aL\x10\tVG\x05UuíaÔ\r\x9d¹\x96ÏaU¥',
                                    PSEUDO_CUSTOMER_ID                           PSEUDO_CUSTOMER_ID_BYTES  PSEUDO_CUSTOMER_ID_STR
  0  [138, 76, 16, 9, 86, 71, 5, 85, 117, 237, 97, ...  b'\x8aL\x10\tVG\x05Uu\xeda\xd4\r\x9d\xb9\x96\x...  L\tVGUuíaÔ\rÏaU¥)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM