我有一个数据帧,其中包含一堆 int 列以及四个额外的列列。 我融化了数据帧。 它按预期工作。 然后我数据透视表它回来了。 这也很好用。 唯一的问题是整数列都从组合熔化\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')
但我得到这个:属性错误:"str"对象没有属性"isin">
目标是将上面"排除"列表中的所有列转换为 int。
我正在关注这篇文章: 如何为 Pandas 数据帧实现"in"和"not in">
这些是列和类型:
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
你可以改做
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)