如何检查pythonpandas中列的dtype

我需要使用不同的函数来处理数字列和string列。 我现在正在做的事情真的很愚蠢:

allc = list((agg.loc[:, (agg.dtypes==np.float64)|(agg.dtypes==np.int)]).columns) for y in allc: treat_numeric(agg[y]) allc = list((agg.loc[:, (agg.dtypes!=np.float64)&(agg.dtypes!=np.int)]).columns) for y in allc: treat_str(agg[y]) 

有没有更优雅的方式来做到这一点? 例如

 for y in agg.columns: if(dtype(agg[y]) == 'string'): treat_str(agg[y]) elif(dtype(agg[y]) != 'string'): treat_numeric(agg[y]) 

您可以使用dtype访问列的数据types:

 for y in agg.columns: if(agg[y].dtype == np.float64 or agg[y].dtype == np.int64): treat_numeric(agg[y]) else: treat_str(agg[y]) 

我知道这是一个古老的线索,但与pandas19.02,你可以这样做:

 df.select_dtypes(include=['float64']).apply(your_function) df.select_dtypes(exclude=['string','object']).apply(your_other_function) 

http://pandas.pydata.org/pandas-docs/version/0.19.2/generated/pandas.DataFrame.select_dtypes.html

pandas 0.20.2你可以这样做:

 from pandas.api.types import is_string_dtype from pandas.api.types import is_numeric_dtype is_string_dtype(df['A']) >>>> True is_numeric_dtype(df['B']) >>>> True 

所以你的代码变成:

 for y in agg.columns: if (is_string_dtype(agg[y])): treat_str(agg[y]) elif (is_numeric_dtype(agg[y])): treat_numeric(agg[y]) 

如果要将数据框列的types标记为string,则可以执行以下操作:

 df['A'].dtype.kind 

一个例子:

 In [8]: df = pd.DataFrame([[1,'a',1.2],[2,'b',2.3]]) In [9]: df[0].dtype.kind, df[1].dtype.kind, df[2].dtype.kind Out[9]: ('i', 'O', 'f') 

你的代码的答案是:

 for y in agg.columns: if(agg[y].dtype.kind == 'f' or agg[y].dtype.kind == 'i'): treat_numeric(agg[y]) else: treat_str(agg[y])