'Get the dtype of specific column with a loop
I want to display all my column with the dtypes.
For this I used to do df.dtypes. But in this dataframe I have 4000 column and I would also like to number them.
I tried something like this:
for i in range(df.shape[1]):
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
print(i ,':',df.dtypes)
This obviously does not give me the expected result but you get the idea of what I need. How can I can use df.dtypes in a loop?
Solution 1:[1]
I'm not 100% sure what you want, but this will print the column number (or some version of it), name and dtype, for the whole dataframe:
for i, (name, dtype) in enumerate(zip(df.columns, df.dtypes)):
print(i, name, dtype)
Solution 2:[2]
If you want to print dtypes of all the columns, you can simply do print(df.dtypes) (but it also print dtype: object at the end).
If you want to print it as your own format, such as using :, you can do, as follows:
import pandas as pd
df = pd.DataFrame({
'A': [1, 2, 3],
'B': ['a', 'b', 'c'],
'C': [1.1, 2.2, 3.3]
})
print(df)
# A B C
#0 1 a 1.1
#1 2 b 2.2
#2 3 c 3.3
print(df.dtypes)
#A int64
#B object
#C float64
#dtype: object
for col_name, dtype in df.dtypes.items():
print(col_name, ":", dtype)
#A : int64
#B : object
#C : float64
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 9769953 |
| Solution 2 |
