如何检查具有多种类型的列中的数据类型?-寻找更好的解决方案

Cha*_*Loi 2 numpy dataframe pandas

数据样本:

a=pd.DataFrame({'Col1':[1,2,'a','b',1.5],'Col2':['a','b','c',2,3],'Col3':['a',1.2,1.3,1.4,2]}))

  Col1 Col2 Col3
0    1    a    a
1    2    b  1.2
2    a    c  1.3
3    b    2  1.4
4  1.5    3    2
Run Code Online (Sandbox Code Playgroud)

正如您在列中看到的那样,有str, int, float

我下面的代码是检查类型并计算它的数量。虽然有点业余,还是请看一下。

def checkDtype(df='DateFrame',s='Series'):
 ListOfType={}
 for i in df.columns:              #Walk through every columns of DataFrame
     ListOfType[i]=dict(Float=0,Int=0,Str=0)
     for a in df[i]:               #Walk through every row of the selected column
         if type(a) is float:
             ListOfType[i]['Float']+=1
         if type(a) is int:
             ListOfType[i]['Int']+=1
         if type(a) is str:
             ListOfType[i]['Str']+=1
 return ListOfType
Run Code Online (Sandbox Code Playgroud)

`

b= checkDtype(df=a)                #The result - put into DataFrame for visual
result=pd.DataFrame(data=[a['Col1'],a['Col2'],a['Col3']],index=['col1','col2','col3'])
result.T 

       col1  col2  col3
Float     1     0     3
Int       2     2     1
Str       2     3     1
Run Code Online (Sandbox Code Playgroud)

我正在寻找更好的解决方案。

此外,如果有人已经“接触”数据并最终将类型更改为 Int64 或 Int32 等,我认为这个应用程序将无法工作。所以请帮我解决这个问题。

ank*_*_91 6

尝试:

a.applymap(type).apply(pd.value_counts).fillna(0)
Run Code Online (Sandbox Code Playgroud)
                 Col1  Col2  Col3
<class 'str'>       2   3.0     1
<class 'int'>       2   2.0     1
<class 'float'>     1   0.0     3
Run Code Online (Sandbox Code Playgroud)