Creating dataframe from dictionary with multiple dtypes set for columns

55 Views Asked by At

I would like to create a pandas dataframe from a dictionary but set multiple dtypes on selected columns at creation. EDIT - should have made this clear - I have already created the dictionary and have passed it in as col_dets in this example.

df = pd.DataFrame(col_dets, index=[0]).astype(dict.fromkeys(df.columns[[3, 6, 9]], 'float64'))

I am aware the above is incorrect, but is there a method to do this? Ideally stating columns at these indices are float64 and at other indices are int64 (for example?)

1

There are 1 best solutions below

2
mozway On

Assuming this is a follow-up of your previous question and that you want to assign a different type based on column position, you could use:

dtypes = {3: 'float32', 6: 'float64', 9: 'complex64'}

df = df.astype(dict(zip(df.columns[list(dtypes)], dtypes.values())))

print(df.dtypes)

Output:

col0       object
col1       object
col2       object
col3      float32
col4       object
col5       object
col6      float64
col7       object
col8       object
col9    complex64
dtype: object

Used input:

col_dets = [f'col{i}' for i in range(10)]
df = pd.DataFrame(columns=col_dets, index=[0])