【问题标题】:Determine if a dtypes Object should be an Int or float确定 dtypes 对象应该是 Int 还是 float
【发布时间】:2019-08-24 17:31:05
【问题描述】:

试图确定列条目的大多数 dtype 是什么。我正在自动化数据帧处理函数,该函数确定对象类是否充满strings 或充满int or float,但其中包含未知的strings。我知道通过键入以下内容,可以识别列的数据类型,但条目呢?

import pandas as pd

df = pd.read_csv('data.csv')
df.dtypes

输出

Name       object
Age        object
dtype: object

识别列是否被错误标记的最佳方法是什么。示例数据在这里

df.Age
Out[25]: 
0          25
1          23
2          24
3          26
4          30
5          18
6          22
7          19
8          23
9          20
10    Refused
11         23
12         29
Name: Age, dtype: object

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以通过DataFrame.select_dtypes 仅查看对象列(显然是strings),然后尝试使用参数errors='coerce' 转换to_numeric - 它会将不可解析的值转换为NaNs,因此请测试是否至少有一个非NaN Series.notnaSeries.any:

    for c in df.select_dtypes(object).columns:
        if pd.to_numeric(df[c], errors='coerce').notna().any():
            print (c)
    

    【讨论】:

      猜你喜欢
      • 2011-08-14
      • 2011-05-31
      • 2017-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多