【问题标题】:How to access categorical data which is saved as object in a dataframe?如何访问在数据框中保存为对象的分类数据?
【发布时间】:2019-06-17 16:43:33
【问题描述】:

我有.dta 数据,我使用df = pd.read_stata('mydata.dta', convert_categoricals=True) 加载。当我从 Stata 转换类别时,我可以更轻松地“看到”我的类别是关于什么的。但我找不到以这种格式处理数据的选项。它实际上被转换为字符串/对象。

我在 SA 上发现了一个没有任何答案的类似问题:Pandas doesnt recognize categorical — access original codes when convert_categorical=True

我的解决方法是不从 dta 转换猫。 df = pd.read_stata('mydata.dta', convert_categoricals=False) 然后可以进行计算等,但我必须手动查找所有类别。那不是很pythonic。

MWE 这种情况真的很难。有点像这样:

import pandas as pd
df = pd.DataFrame({'year': ['1988', '1988', '1988', '1988', '1989', '1989', '1989', '1989'],
                  'money': ['5', '7', '8', '8', '3', '3', '7', '8']}).astype(int)

health = ['2 [good]', '-2 [not applicable]', '3 [ok]', '1 [excellent]', '3 [ok]', '5 [bad]', '2 [good]', '1 [excellent]']
df['health'] = health
df.info() # health is an object

# df.loc[(df.health >= 2) & (df.year=1988), 'money'] # not working

在我的分析中,我想检查给定年份身体健康的人的钱。但是类别是字符串。我有很多变量和类别。

如何告诉数据框使用“括号前的数字”?

处理数据框中类别的“值”和“标签”的正确方法是什么?正确的数据类型是什么?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    这里有必要使用Series.str.extracthealth 值获取新列的值:

    df[['a','b']] = df['health'].str.extract('([-]?\d+)\s+\[(.+)\]')
    df['a'] = df['a'].astype(int)
    print (df)
       year  money               health  a               b
    0  1988      5             2 [good]  2            good
    1  1988      7  -2 [not applicable] -2  not applicable
    2  1988      8               3 [ok]  3              ok
    3  1988      8        1 [excellent]  1       excellent
    4  1989      3               3 [ok]  3              ok
    5  1989      3              5 [bad]  5             bad
    6  1989      7             2 [good]  2            good
    7  1989      8        1 [excellent]  1       excellent
    

    【讨论】:

    • 所以我总是要从字符串中提取数值?跟踪“含义/标签”的唯一方法是将其保存到另一列?我的意思是,我有 10 个这样的变量,它应该仍然是可能的。但对我来说它看起来不是很优雅。有没有办法将值和标签存储在 df 的一个单元格中?最好的问候
    • @MarcoDoe - 这取决于你需要什么。如果在列中使用标量,则最好的 pandas 工作 - 所以数字列分开,字符串列分开。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 2020-03-20
    相关资源
    最近更新 更多