将熊猫列的子集转换为int

时间:2019-07-25 12:30:15

标签: python-3.x pandas

我有一个带有一堆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

1 个答案:

答案 0 :(得分:0)

您可以代替

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)