python - 使用 pandas DataFrame 中的 loc 将 pandas.to_numeric 应用于选定的列子集

标签 python pandas

如何将 pandas.to_numeric 应用于使用 .loc[] 选择的 DataFrame 子集?例如。考虑这个 DataFrame:

df = pd.DataFrame(index=pd.Index([1, 2, 3]))
df['X'] = ['a', 'a', 'b']
df['Y'] = [1, 2, 3]
df['Z'] = [4, 5, 6]
df['Y'] = df['Y'].astype(object)
df['Z'] = df['Z'].astype(object)
df
    X   Y   Z
1   a   1   4
2   a   2   5
3   b   3   6

注意 Y 和 Z 列的类型是 object。 我想在 Y 和 Z 列上应用 pandas.to_numeric 以将数据类型更改为 int。我测试了 3 种方法:

df.loc[:, 'Y'] = df.loc[:, 'Y'].apply(pd.to_numeric) # (1) WORKS
df.loc[:, 'Z'] = df.loc[:, 'Z'].apply(pd.to_numeric) # (1) WORKS

df.loc[:, ['Y', 'Z']] = df.loc[:, ['Y', 'Z']].apply(pd.to_numeric) # (2) DOESN'T WORK

df.loc[:, 'Y':'Z'] = df.loc[:, 'Y':'Z'].apply(pd.to_numeric) # (3) DOESN'T WORK

方法 (3) 和 (4) 不适用于 pd.to_numeric,但适用于其他函数,例如

df.loc[:, 'Y':'Z'] = df.loc[:, 'Y':'Z'].apply(lambda x: x*0)

正确地将 Y 和 Z 列设置为零。有人可以解释为什么它不适用于 pandas.to_numeric 吗?

编辑

最后,事实证明这种行为是有意为之的,因为 .loc[:, ...][] 之间存在差异。根据文档:

Note: When trying to convert a subset of columns to a specified type using astype() and loc(), upcasting occurs. loc() tries to fit in what we are assigning to the current dtypes, while [] will overwrite them taking the dtype from the right hand side.

因此,应按照 jezrael 的回答中的建议使用 [] 更改类型。更多信息在 documentation .

最佳答案

看起来像错误。

对我来说工作:

df[['Y', 'Z']] = df[['Y', 'Z']].apply(pd.to_numeric)
print (df.dtypes)
X    object
Y     int64
Z     int64
dtype: object

关于python - 使用 pandas DataFrame 中的 loc 将 pandas.to_numeric 应用于选定的列子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46629493/

相关文章:

python - 使用 Python locals() 进行字符串格式化有缺点吗?

python - Python 中的大多数除数

python - 使用正则表达式来约束元组列表

python - 如何在 Windows 7 计算机上将模块上传到 Python 测试站点(https ://testpypi. python.org/pypi)?

python - 从 numpy 3d 数组创建一个整洁的 pandas 数据框

python - 在 Django 中减去日期时间 - 无输出

python - Python 会缓存重复访问的文件吗?

Python pandas dataframe 插入缺失数据

python - pandas,使用func pandas.Series.value_counts后如何获取索引?

python - 使用多索引列堆叠多索引数据框