Why can't I get the type of a Pandas cell from a function?

Zub*_*ubo 4 python pandas

I'd like to get the type of argument I'm passing to a function (I think it's a Pandas Series, but I want to make sure) and write into a new column in a Pandas Dataframe. Why does this

data = np.array([['','Col1','Col2', 'Col3'],
                ['Row1','cd, d', '1, 2', 'ab; cd'],
                ['Row2','e, f', '5, 6', 'ef; gh'],
                ['Row3','a, b', '3, 4', 'ij; kl']])

df = pd.DataFrame(data=data[1:,1:],
                  index=data[1:,0],
                  columns=data[0,1:])

def find_type(my_arg):
    return type(my_arg)

df['types'] = find_type(df['Col1'])
Run Code Online (Sandbox Code Playgroud)

give me

AttributeError: 'int' object has no attribute 'index'
Run Code Online (Sandbox Code Playgroud)

and what's the right way to do this?

Rag*_*elt 5

You're looking for pandas.DataFrame.dtypes.

>>> df.dtypes
Col1    object
Col2    object
Col3    object
dtype: object

>>> dict(df.dtypes)
{'Col1': dtype('O'), 'Col2': dtype('O'), 'Col3': dtype('O')}

>>> df['Col1'].dtypes
dtype('O')
Run Code Online (Sandbox Code Playgroud)

If you do type(df['Col1']), Python will tell you that the type is pandas.core.series.Series which isn't particularly useful. You need to determine the type of data stored in the column, not that the column is implemented as a series.


Joh*_*hnE 5

如果这有帮助,数据帧的列(是系列)有一个像 float64、int32 或 object 这样的 dtype,其中 object 基本上是非数字(如字符串)的集合。

除此之外,细胞还可以有类型。如果 dtype 是某种整数或浮点数,那么单元格也将是整数或浮点数。如果 dtype 是对象,那么单元格可以是任何东西,包括类型的混合。

下面是一个例子:

>>> df=pd.DataFrame({'a':[1.1,2.2],'b':[1,2],
                     'c':['cat','dog'],'d':['rat',3]})

>>> df.dtypes

a    float64
b      int64
c     object
d     object
dtype: object

>>> df.applymap(type)

                 a              b              c              d
0  <class 'float'>  <class 'int'>  <class 'str'>  <class 'str'>
1  <class 'float'>  <class 'int'>  <class 'str'>  <class 'int'>
Run Code Online (Sandbox Code Playgroud)

我不确定这是否有帮助或您正在尝试做什么,但我找不到可以链接到的简单解释,所以我想我会很快写下来。