Reputation: 41
Suppose I have a dataframe with different types. Let there be columns of float, string and int.
A B C
1 car 4.3 302
2 Lena -1.2 4
3 I 9.1 18
How do I get a column with type 'float'?
while not referring to the column name directly.
Upvotes: 1
Views: 191
Reputation: 640
You can use List Comprehensions for this:
Here's a sample dataframe:
import pandas as pd
df = pd.DataFrame({'one' : pd.Series([10, 0, 10, 9], index=['a', 'b', 'c', 'd']), //
'two' : pd.Series([0, 0, 10., 4.6], index=['a', 'b', 'c', 'd']), //
'three' : pd.Series(['aaa', 'abc', 'def', 'fff'], index=['a', 'b', 'c', 'd'])})
print(df)
"""
one two three
a 10 0.0 5
b 0 0.0 -1
c 10 10.0 7
d 9 4.6 -1
"""
what are my column types?
for col in df.columns:
print('col : ',col, ' , datatype: ',df[col].dtype)
"""
col: one , datatype: int64
col: two , datatype: float64
col: three , datatype: object
"""
Return columns of type 'float'
print(df[[col for col in df.columns if df[col].dtype == 'float']])
"""
two
a 0.0
b 0.0
c 10.0
d 4.6
"""
Return multiple column types (float and int64)
print(df[[col for col in df.columns if df[col].dtype in ['float','int64']]])
"""
one two
a 10 0.0
b 0 0.0
c 10 10.0
d 9 4.6
"""
Upvotes: 0
Reputation: 4827
You can try:
df.select_dtypes(float)
or
df.loc[:, df.dtypes == float]
Upvotes: 2
Reputation: 153460
Use, select_dtypes
:
df.select_dtypes(include='float')
Output:
B
1 4.3
2 -1.2
3 9.1
Upvotes: 2