Saturday 4 August 2018

Pandas exercise 1

>>>>import pandas as pd
>>>df = pd.DataFrame({"val": list(zip(range(9), range(9)[::-1]))})
>>>df 

use query to subset the df using the first entry(>3) of the tuple. 
      val
0  (0, 8)
1  (1, 7)
2  (2, 6)
3  (3, 5)
4  (4, 4)
5  (5, 3)
6  (6, 2)
7  (7, 1)
8  (8, 0)
Solution:
#Access the first elements of the tuple
>>> df.val.str[0]
0    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
>>> df.val.str[0].to_frame().query('val > 3')
   val
4    4
5    5
6    6
7    7
8    8
.str will work with any object column (this includes columns of lists and tuples), not just strings (strings are considered objects, one of many possible types).

No comments:

Post a Comment

list operations in python

How to make each term of an array repeat, with the same terms grouped together? i/p: [A,B,C] o/p: [A,A,A,B,B,B,C,C,C] Solution: >...