看起来dtype
只对pandas.DataFrame.Series
起作用,是吗?有没有一种可以同时显示所有列数据类型的函数?
看起来dtype
只对pandas.DataFrame.Series
起作用,是吗?有没有一种可以同时显示所有列数据类型的函数?
单数形式的dtype用于检查单个列的数据类型。而复数形式的dtypes用于数据帧,返回所有列的数据类型。基本上:
对于单个列:
dataframe.column.dtype
对于所有列:
dataframe.dtypes
例子:
import pandas as pd
df = pd.DataFrame({'A': [1,2,3], 'B': [True, False, False], 'C': ['a', 'b', 'c']})
df.A.dtype
# dtype('int64')
df.B.dtype
# dtype('bool')
df.C.dtype
# dtype('O')
df.dtypes
#A int64
#B bool
#C object
#dtype: object
假设df是一个Pandas DataFrame,则要同时获取所有列的非空值数量和数据类型,请使用:
```df.info()```
df.info()
df.dtypes.to_dict()
非常方便。my_type = 'float64'
dtypes = dataframe.dtypes.to_dict()
for col_name, typ in dtypes.items():
if (typ != my_type): #<---
raise ValueError(f"Yikes - `dataframe['{col_name}'].dtype == {typ}` not {my_type}")
您会发现,Pandas在比较NumPy类和用户提供的字符串方面做得非常出色。例如:即使像'double' == dataframe['col_name'].dtype
这样的东西,在 .dtype==np.float64
时也会成功。
import pandas as pd
from pandas.api.types import is_object_dtype, is_numeric_dtype, is_bool_dtype
df = pd.DataFrame({'A': [1,2,3], 'B': [True, False, False], 'C': ['a', 'b', 'c']})
is_numeric_dtype(df['A'])
>>> True
df.info()
或者 df.dtypes
会显示一些列的总体统计信息或者顶部和底部的某些列。<class 'pandas.core.frame.DataFrame'>
Int64Index: 4387 entries, 1 to 4387
Columns: 119 entries,
CoulmnA to ColumnZ
dtypes: datetime64[ns(24),
float64(54), object(41)
memory usage: 4.0+ MB
这只是提供24个日期时间列、54个float64列和41个object列的数据类型信息。
如果您想要一条命令获取每列的数据类型,请执行以下操作:
dict(df.dtypes)
您还可以通过使用 dataframe_name.column_name 间接查看它,该方法会显示列值以及其数据类型。
例如:
import pandas as pd
data = {"strings" : ["a","b","c"], "ints" : [1,2,3]}
df = pd.DataFrame(data)
print(df.strings)
print("------------")
print(df.ints)
这将输出:
0 a
1 b
2 c
Name: strings, dtype: object
------------
0 1
1 2
2 3
Name: ints, dtype: int64
df.dtypes[df.dtypes != 'int64'][df.dtypes != 'float64']
- nishantpandas
文档,其中提到:“Pandas使用对象dtype来存储字符串”。 - call-in-codf.C.dtype
返回dtype('O')
,但是df.C.dtype=='object'
是正确的。 - Teepeemm