iraciv94
iraciv94

Reputation: 840

Creating column with datatypes with pandas

I have a DataFrame df:

A   B
1   dog 
cat XX 

I have been trying to create a pandas DataFrame df_new that looks like this:

A   B    type_of_A   type_of_B
1   dog  int         string
cat XX   string      whateverdtype it may be

I tried with:

df_new["type_of_A"] = [pd.api.types.infer_dtype(i) for i in range(df_new['A'].values)]

But I only got:

TypeError: only integer scalar arrays can be converted to a scalar index

Can anyone give me a hint? is this the right approach?

Thanks so much in advance

Upvotes: 0

Views: 52

Answers (1)

BENY
BENY

Reputation: 323366

Using applymap with type, the concat back

s=df.applymap(type).add_prefix('type_of_')
df=pd.concat([df,s],1)
Out[543]: 
     A    B      type_of_A      type_of_B
0    1  dog  <class 'int'>  <class 'str'>
1  cat   XX  <class 'str'>  <class 'str'>

Upvotes: 3

Related Questions