【问题标题】:Convert a subset of pandas columns to int将 pandas 列的子集转换为 int
【发布时间】:2019-07-25 12:30:15
【问题描述】:

我有一个包含一堆 int 列加上四个额外的数据框 列。我融化了数据框。它按预期工作。然后我将数据透视表 回来了。这也很好用。唯一的问题是整数列 都从组合的 melt\pivot_table 操作转换为 float64。 注意:受影响列中的每个值都只是零 (0) 或一 (1)。我最终得到 1.0 或 0.0。我想将它们转换回 int。

这是有问题的代码块。

exclude = ['Title', 'Votes', 'Rating', 'Revenue_Millions']
for col in re_reshaped_df.columns:
    if ~col.isin(exclude):
        re_reshaped_df[col] = re_reshaped_df[col].astype('int')

但我得到了这个: AttributeError: 'str' 对象没有属性 'isin'

目标是将所有不在上面“排除”列表中的列转换为 int。

我在关注这个帖子: How to implement 'in' and 'not in' for Pandas dataframe

这些是列和类型:

Title                object
Rating              float64
Votes                 int64
Revenue_Millions    float64
Action              float64
Adventure           float64
Animation           float64
Biography           float64
Comedy              float64
Crime               float64
Drama               float64
Family              float64
Fantasy             float64
History             float64
Horror              float64
Music               float64
Musical             float64
Mystery             float64
Romance             float64
Sci-Fi              float64
Sport               float64
Thriller            float64
War                 float64
Western             float64

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    你可以这样做

    exclude = ['Title', 'Votes', 'Rating', 'Revenue_Millions']
    for col in re_reshaped_df.columns:
        if col not in exclude:
            re_reshaped_df[col] = re_reshaped_df[col].astype('int')
    

    因为这里你的col 变量是一个列名,所以是一个字符串而不是Series,所以pandas 方法将不起作用。 解决此问题的另一种方法是:

    exclude = ['Title', 'Votes', 'Rating', 'Revenue_Millions']
    ix = re_reshaped_df.columns.drop(exclude)
    re_reshaped_df.loc[:,ix] = re_reshaped_df.loc[:,ix].astype(int)
    

    【讨论】:

    • 我编辑了我的第二种方法,因为我在第一次尝试时使用了交集而不是 drop
    • 仅供参考,第二种方法出错了。 TypeError:'(切片(无,无,无),索引(['动作','冒险','动画','传记','喜剧','犯罪','戏剧','家庭','幻想','历史','恐怖','音乐','音乐','神秘','浪漫','科幻','运动','惊悚','战争','西部'],dtype ='object', name='Genre'))' 是无效键
    • 对不起,我刚刚重新编辑了它,我忘记了loc的东西
    • 就是这样。非常感谢。
    猜你喜欢
    • 2020-08-24
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 2014-02-12
    • 2021-11-02
    • 2017-09-26
    相关资源
    最近更新 更多