如何将 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()
andloc()
, 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/