﻿ Pandas: Select columns by data type of a given DataFrame - w3resource

# Pandas: Select columns by data type of a given DataFrame

## Pandas: DataFrame Exercise-66 with Solution

Write a Pandas program to select columns by data type of a given DataFrame.

Sample Solution :

Python Code :

``````import pandas as pd
df = pd.DataFrame({
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Syed Wharton'],
'date_of_birth': ['17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'age': [18.5, 21.2, 22.5, 22, 23]
})

print("Original DataFrame")
print(df)
print("\nSelect numerical columns")
print(df.select_dtypes(include = "number"))
print("\nSelect string columns")
print(df.select_dtypes(include = "object"))
``````

Sample Output:

```Original DataFrame
name date_of_birth   age
0  Alberto Franco    17/05/2002  18.5
1    Gino Mcneill    16/02/1999  21.2
2     Ryan Parkes    25/09/1998  22.5
3    Eesha Hinton    11/05/2002  22.0
4    Syed Wharton    15/09/1997  23.0

Select numerical columns
age
0  18.5
1  21.2
2  22.5
3  22.0
4  23.0

Select string columns
name date_of_birth
0  Alberto Franco    17/05/2002
1    Gino Mcneill    16/02/1999
2     Ryan Parkes    25/09/1998
3    Eesha Hinton    11/05/2002
4    Syed Wharton    15/09/1997
```

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## Python: Tips of the Day

Inserting if statements using conditional list comprehensions:

```x = [1, 2, 3, 4, 5, 6]
result = []
for idx in range(len(x)):
if x[idx] % 2 == 0:
result.append(x[idx] * 2)
else:
result.append(x[idx])
result
```

Output:

```[1, 4, 3, 8, 5, 12]
```
`[(element * 2 if element % 2 == 0 else element) for element in x]`

Output:

```[1, 4, 3, 8, 5, 12]
```
`[element * 2 for element in x if element % 2 == 0]`

Output:

```[4, 8, 12]
```