【问题标题】:Convert each cell of a Pandas's column from list to word-count dictionary?将 Pandas 列的每个单元格从列表转换为字数字典?
【发布时间】:2016-06-06 06:35:04
【问题描述】:

DataFrame 有一列df['Title'],其中每一行都是在某个位置销售的一本书,LOCATION_ID。我想将dfLOCATION_ID 分组,并创建一个包含两列的新DataFrame:LOCATION_IDTitle-Count每个位置出售的书籍的字典。

具体来说,我正在尝试做类似的事情:

from collections import Counter
new_df = df.groupby('LOCATION_ID')['TITLE'].apply(lambda x: Counter(x))

我期待这样的输出:

LOCATION_ID  |     TITLES
1                 {'TitleA':12; 'TitleB':56 ; ...}
2                 {'TitleK':5; 'TitleC':23 ; ...}
...

但相反,我收到的是这样的:

LOCATION_ID                         Title                             
1               TitleA               12
                TitleB               56
...
2               TitleK              5
                TitleG              23
...

感谢您的帮助。

【问题讨论】:

  • 您当前的输出有什么问题?看起来,输出就是你想要的。为什么需要字典?
  • TITLES 将成为逻辑分类器的特征。我要使用的库方法需要字典格式。
  • 你会使用 Scikit-learn 吗?
  • 您能提供一个输入样本吗?
  • @Joe R 我正在使用graphlab 的logistic_classifier。我想估计: book_model = graphlab.logistic_classifier.create(train_data, target='books_sold', features=['book_count'], validation_set=test_data)d

标签: python dictionary pandas counter


【解决方案1】:

使用agg 代替apply

import numpy as np
import pandas as pd
from collections import Counter
prng = np.random.RandomState(0)
df = pd.DataFrame({'LOCATION_ID': prng.choice([1, 2, 3], 1000), 'TITLE': [''.join(prng.choice(list("abcd"), 3)) for _ in range(1000)]})
df.head()
Out[9]: 
   LOCATION_ID TITLE
0            1   bbb
1            2   bab
2            1   daa
3            2   dcd
4            2   cbc

df.groupby('LOCATION_ID')['TITLE'].apply(lambda x: Counter(x)).head()
Out[10]: 
LOCATION_ID     
1            aaa    2.0
             aab    5.0
             aac    4.0
             aad    3.0
             aba    8.0
dtype: float64

df.groupby('LOCATION_ID')['TITLE'].agg(lambda x: Counter(x))
Out[11]: 
LOCATION_ID
1    {u'cbb': 5, u'cbc': 8, u'cba': 6, u'cda': 8, u...
2    {u'cdd': 5, u'cbc': 7, u'cbb': 1, u'cba': 4, u...
3    {u'cbb': 6, u'cbc': 7, u'cba': 4, u'cda': 6, u...
Name: TITLE, dtype: object

您的期望是有道理的。当您将项目组合在一起时,您希望 pandas 返回分组结果。但是,groupby.apply 记录为 flexible apply。根据返回的对象,它推断如何组合结果。在这里,它看到一个字典并为您提供更好的输出,它创建了一个多索引系列。

【讨论】:

    猜你喜欢
    • 2020-11-28
    • 2021-11-08
    • 2019-10-27
    • 2022-10-13
    • 2022-01-19
    • 1970-01-01
    • 2014-01-05
    • 2021-11-28
    相关资源
    最近更新 更多