hernanavella hernanavella - 4 years ago 145
Python Question

How to slice df by col name when some of the columns are of datetime.time type?

Given a df of this type:

A = pd.DataFrame(
[[1, 5, 2, 8, 2], [2, 4, 4, 20, 2], [3, 3, 1, 20, 2], [4, 2, 2, 1, 0], [5, 1, 4, -5, -4],
[1, 5, 2, 2, -20], [2, 4, 4, 3, 0], [3, 3, 1, -1, -1], [4, 2, 2, 0, 0], [5, 1, 4, 20, -2]],
columns=[datetime.time(8, 20), datetime.time(8, 30), '0 009', 'name', datetime.time(9, 0)],
index=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
)


Im trying to select some columns by name like:

b = A[[col for col in A if "0 " in col or "name" in col]]


However, I got an error:


TypeError: argument of type 'datetime.time' is not iterable


How can I slice the df by column name when some of the columns are of
datetime.time
type?

An alternative path is to select first the columns which name is a string and then I can use the procedure I intended originally.

Answer Source

Pandas offers a method called filter which selects specific columns based on their name. You can select these columns in different ways with regex being one of them. Looking at the source code, the columns are converted to strings when using like or regex but not items so this should work for datetime column names.

A.filter(regex='0 |name')

    0 009  name
1       2     8
2       4    20
3       1    20
4       2     1
5       4    -5
6       2     2
7       4     3
8       1    -1
9       2     0
10      4    20
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download