python - 为什么 select_dtypes 在这种情况下在 pandas 中不起作用

标签 python pandas

    import pandas as pd

    import numpy as np

    test_df = pd.DataFrame([[1,2]]*4, columns=['x','y'])

    test_df.iloc[0,0] = '1'
    test_df.iloc[0,0] = 1

    test_df.select_dtypes(include=['number'])

我想知道为什么本例中不包含 x 列

最佳答案

我可以在 Pandas v0.19.2 上重现。问题是 Pandas 何时(如果有的话)选择检查并重铸系列。您首先使用以下赋值将系列定义为 dtype object:

test_df.iloc[0, 0] = '1'

Pandas 将任何带有字符串的系列存储为 object dtype。然后,您可以覆盖下一行中的值,而无需显式更改该系列的数据类型:

test_df.iloc[0, 0] = 1

但是您不应该假设这会自动触发整个系列转换为数字数据类型。据我所知,这不是有记录的行为。虽然它可能适用于较新的版本,但这不是您应该为生产工作流程假定的行为。

关于python - 为什么 select_dtypes 在这种情况下在 pandas 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52943458/

相关文章:

来自两个不重叠范围的 Python 随机唯一值

python - get_dumies 出现无法散列的类型 'list' 错误

python - 索引错误 : positional indexers are out-of-bounds stratify sklearn test_train_split

python - 转换 pandas.DataFrame 中的元组列表

python - 使用多个日期时间列作为条件获取计数时遇到问题

Python 字典到 CSV

python - Keras - 复制 Conv2D 层

Python concurrent.futures - 未调用方法

python - 如何使用 json_normalize 规范化嵌套 json

python - utf-8和utf-8-sig有什么区别?