0

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

1 Answer 1

3

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'>
Sign up to request clarification or add additional context in comments.

2 Comments

is there a way to apply this procedure to individual columns instead to the whole df? because I believe that "applymap" does not work on series.
@iraciv94 just do s.apply(type) for series

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.