-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpandas-exercises.py
More file actions
1881 lines (1638 loc) · 61.2 KB
/
Copy pathpandas-exercises.py
File metadata and controls
1881 lines (1638 loc) · 61.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
'''
10 Minutes to pandas
http://pandas.pydata.org/pandas-docs/stable/10min.html#min
100 Pandas Exercises (see below)
https://github.com/ajcr/100-pandas-puzzles
'''
# error in Spyder
https://github.com/spyder-ide/spyder/issues/2991
https://github.com/pydata/pandas/issues/9950
pd.get_option('display.float_format') # None
pd.reset_option('display.float_format') # set the default
pd.describe_option('display.float_format')
pd.set_option('display.float_format', lambda x:'%f'%x) # fixes this issue
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Creating a Series by passing a list of values,
# letting pandas create a default integer index:
s = pd.Series([1,3,5,np.nan,6,8])
s
# Creating a DataFrame by passing a numpy array,
# with a datetime index and labeled columns:
dates = pd.date_range('20130101', periods=6)
dates
df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
df
# Creating a DataFrame by passing a dict of objects
# that can be converted to series-like.
df2 = pd.DataFrame({ 'A' : 1.,
'B' : pd.Timestamp('20130102'),
'C' : pd.Series(1,index=list(range(4)),dtype='float32'),
'D' : np.array([3] * 4,dtype='int32'),
'E' : pd.Categorical(["test","train","test","train"]),
'F' : 'foo',
'G' : pd.Series(np.arange(4)),
'H' : np.arange(4),
'I' : [4,3,2,1] })
df2
df2.dtypes
df2.A
df2.B
df2.C
df2.D
df2.F
df2.G
df2.H
df2.I
# See the top & bottom rows of the frame
df.head()
df.tail()
# Display the index, columns, and the underlying numpy data
df.index
df.columns
df.values
df2.index
df2.columns
df2.values # a list of lists (=a list of rows, each row being a list of elements)
# Describe shows a quick statistic summary of your data
df.describe
df.T
df.sort_index(axis=1, ascending=False) # sort by an axis (by column labels?)
'''
Interactive work:
standard Python / Numpy expressions for selecting and setting
Production code:
the optimized pandas data access methods, .at, .iat, .loc, .iloc and .ix
'''
# selecting columns by labels, and rows by row numbers
# here: standard slices (the last excluded)
df['A'] # Selecting a single column, which yields a Series
df["A"]
df.A
df.A[dates[0]]
df[0:3] # row slices
df['20130102':'20130104']
# mixed
df.A[dates[0]]
df[0:3].A
df[0:3,'A'] # key error or type error *unhashable type 'slice'
# selection by label
# here: slices with the last included
# fast scalar selection: at()
df
dates[0]
df.loc[dates[0]] # a row selected; cross section by label
df.loc['A'] # error: row label (=index) expected
df.loc[:,['A','B']] # multi-axis by label
df.loc['20130102':'20130104',['A','B']] # both endpoints included
df.loc['20130102',['A','B']] # reduction in the dimensions of the returned object
df.loc[dates[0],'A'] # scalar value
df.at[dates[0],'A'] # fast access to a scalar
# selecting by integer position
# fast scalar selection: iat()
df.iloc[3] # select row 3 (the 4th one)
df.iloc[3:5,0:2] # by integer slices (lithe python/numpy)
df.iloc[[1,2,4],[0,2]] # by integer positions
df.iloc[1:3,:] # slicing rows explicitly
df.iloc[:,1:3] # slicing columns explicitly
df.iloc[1,1] # getting a value explicitly
df.iat[1,1] # fast access to a scalar
# Boolean Indexing
df[df.A>.5] # single column values to select rows
df[df>0] # selecting by 'where', NaNs imputed for not-selected values
df2 = df.copy()
df2['E'] = ['one', 'one','two','three','four','three']
df2
df2['E'].isin(['two','four']) # filtering with 'isin()'
df2[df2['E'].isin(['two','four'])]
# setting
# creating a series
s1 = pd.Series([1,2,3,4,5,6], index=pd.date_range('20130102', periods=6))
s1
df.at[dates[0],'A'] = 0 # set value by label: loc(), at()
df.iat[0,1] = 0 # set value by (integer) position: iloc(), iat()
df.loc[:,'D'] = 5 # set many values with a scalar
df.loc[:,'D'] = np.array([5]) # set many values with a singleton
df.loc[:,'E'] = np.array([5] * len(df)) # set many values with a numpy array (by label)
df
df.iloc[2:4,3:5] = np.arange(4).reshape(2,2) # set many values with a numpy array (by position)
df
df2 = df.copy()
df2[df2 > 0] = -df2 # where operation with setting
df2
''' missing data '''
# np.nan
# by default not included in computations
# Reindexing allows you to change/add/delete the index on a specified axis.
# This returns a copy of the data.
df1 = df.reindex(index=dates[0:4], columns=list(df.columns) + ['E'])
df1 # a copy, new dataframe with a new column E filled with NANs
df1.loc[dates[0]:dates[1],'E'] = 1
df1
df1.dropna() # complete cases only
df1.dropna(how='any') # same
df1.dropna(axis=0,how='any') # same
df1.dropna(axis='index',how='any') # same
df1.dropna(axis=1) # drop columns with NANs
df1.dropna(axis='columns') # same
df1.dropna(how='all') # rows where all values are nans
df1.loc[dates[2],'D'] = np.nan
df1
df1.dropna(thresh=4) # drop rows that have less than 4 values
df1.dropna(subset=['C','D']) # drop rows that have NANs in columns C or D
inplace=True # modify the DF, return None
?pd.DataFrame.fillna # use inplace=T if in place
df1.fillna(value=5) # fill missing data with 5
pd.isnull(df1) # boolean mask of nans
# select elements that are not null
df1[not pd.isnull(df1)] # doesn't work element-wise
not pd.isnull(df1) # doesn't work element-wise
pd.isnull(df1).apply(lambda x: x.apply(lambda x: not x)) # long, applied to each column, then to each element in the column
pd.isnull(df1).applymap(lambda x: not x) # shorter, applied to each element in each column
np.logical_not(pd.isnull(df1).as_matrix()) # using numpy
np.logical_not(pd.isnull(df1)) # the same simpler!
np.invert(pd.isnull(df1)) # using numpy
(pd.isnull(df1)*(-1)).astype('bool') # it converts into integer in between
-pd.isnull(df1) # short
~pd.isnull(df1) # short
df1[pd.isnull(df1)] # dropped elements are filled with NaN
df1[~pd.isnull(df1)]
# substitution
df1[pd.isnull(df1)] = 555 # works
''' operations '''
# Operations in general exclude missing data.
df.mean() # mean for each col
df.mean(1) # mean for each row
df.mean(0) # mean for each col
# shifting
s = pd.Series([1,3,5,np.nan,6,8], index=dates).shift(2)
s # shifting dropps the elements at the end and introduces NaNs at the front
# subrtacting, adding, etc.
?pd.DataFrame.sub # with broadcasting
# it tries to fit subtrahends elements to minuend elements by
# column labels (default) or row indeces
# If fit is found -> subtraction is performed accross the column (row).
# If no fit -> NaNs are introduced.
df
df.sub(s, axis='index') # subtract s from columns of df (so along the index)
# index of s fits to the index of df (both are dates)
s2 = pd.Series([1,2,3,4], index=['a','b','c','d'])
s2
df.sub(s2) # just NaNs
# be defualt the fit is by column labels - but there's no fit
# as df has capital letters and s2 has small letters
# the small letters are added as new columns
s3 = pd.Series([1,2,3,4], index=['A','B','C','d'])
s3
df.sub(s3) # works OK
df.add(s3)
df.mul(s3)
df.div(s3)
df.sub(s3, axis='index') # new rows and NaNs only
# the s2 index is letters, while df index is dates
# no fit, new rows added to the index, NaNs introducted
# apply
df.A[0]
df.A[1]
df.A[0]+df.A[1]
np.cumsum(df.A) # can't use the axis argument of numpy for a pandas df
df.apply(np.cumsum) # apply along columns
df.apply(np.cumsum, axis=1) # apply along rows
# count
s = pd.Series(np.random.randint(0, 7, size=10))
s
s.value_counts()
np.bincount(s) # numpy counter part
# Vectorized String Methods
s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
s
s.str.lower()
s.str.split('_') # nothing to split, so 1-element lists returned
s.str.split('a') # see the splitting
s.str.replace('a', '?') # see replacing
# Merge
df = pd.DataFrame(np.random.randn(10, 4))
df
pieces = [df[:3], df[3:7], df[7:]]
pieces # a list of data frames
pd.concat(pieces) # back to the initial single data frame
# default: rstack(), but you can have also cstack()
pd.concat(pieces, axis=1) # concatenating by columns - but preserving the original indexing
# join
left = pd.DataFrame({'key': ['foo', 'bfoo'], 'lval': [1, 2]})
right = pd.DataFrame({'key': ['foo', 'bfoo'], 'rval': [4, 5]})
left
right
pd.merge(left, right, on='key') # correct
pd.concat([left, right], axis=1, join='inner') # this is just stacking columns together
# with rows of the same index put next to each other
# append
df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
df
s = df.iloc[3]
s
df.append(s, ignore_index=True) # appended at the end of df (as the last row)
# this sets a proper index for the added row, here it's '8'
x = df.append(s, ignore_index=False) # by default doesn't check the index integrity
x # this leaves the index as it is, here we have two rows indexed by '3'
x.loc[3] # selects two rows
x.iloc[3] # selects one row
x.loc[8] # key error (no such row label)
x.iloc[8] # selects one row
x.ix[3] # works as label location (the default) so selects two rows
x.ix[8] # error! strange, there's no row labelled 8, but there's row having position 8
''' Grouping:
Splitting the data into groups based on some criteria
Applying a function to each group independently
Combining the results into a data structure
'''
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C' : np.random.randn(8),
'D' : np.random.randn(8)})
df
df.groupby(['A']).sum()
df.groupby(['A','B']).sum()
''' reshaping '''
# stack
[['bar', 'bar', 'baz', 'baz',
'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two',
'one', 'two', 'one', 'two']]
list(zip(['bar', 'bar', 'baz', 'baz',
'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two',
'one', 'two', 'one', 'two']))
list(zip(*[['bar', 'bar', 'baz', 'baz', # the same
'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two',
'one', 'two', 'one', 'two']]))
# explanation:
# * gets out the two sub-lists of the initial lists
# these are passed as two arguments to zip function
# zip creates tuples of respective pairs of elements from the two lists
# the tuples are gathered into one list
tuples = list(zip(*[['bar', 'bar', 'baz', 'baz',
'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two',
'one', 'two', 'one', 'two']]))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
index
''' This is an index consisting of two indeces, named first and second.
Each in turn is a 'factor', with given levels (bar, baz... and one, two)
and with an integer vector indicating the indeces values (the labels).'''
x = np.random.randn(8, 2)
x # 8 rows, 2 columns
df = pd.DataFrame(x, index=index, columns=['A', 'B'])
df
'''
This is a data frame with two columns A and B
and 8 rows indexed by a doubled index: (bar..., one...)
'''
# this multi indexing is hierarchical
df.loc['bar'] # DataFrame
df.loc['baz']
df.loc['one'] # error
df.loc['bar','one'] # ok
df.loc[('bar','one')] # ok
df.loc['bar'].loc['one'] # ok
df.loc['bar']['one'] # error, this asks for a column
df.loc['bar']['A'] # Series; rows (by index 'first') x column A
df.loc[:,'A'] # Series; whole column A
df.loc['bar','one']['A'] # Scalar; row x col -> a scalar, names & dims dropped
df2 = df[:4]
df2
# melting (cmp R reshape2 / tidyr)
df
stacked = df.stack() # R melt / gather
stacked
df.stack(0)
df.stack(1) # error, index has only 1 level, not 2
# casting
# R dcast / spread
stacked
stacked.unstack() # by default: the last level
stacked.unstack(0) # column 0 turned into variables/columns
stacked.unstack(1) # column 1 turned into variables/columns
stacked.unstack(2) # column 2 turned into variables/column (correct reversal)
# Pivot Tables
df = pd.DataFrame({'A' : ['one', 'one', 'two', 'three'] * 3,
'B' : ['A', 'B', 'C'] * 4,
'C' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 2,
'D' : np.random.randn(12),
'E' : np.random.randn(12)})
df
pd.pivot_table(df, values='D', index=['A','B'], columns='C')
''' Time Series
performing resampling operations during frequency conversion
(e.g., converting secondly data into 5-minutely data) '''
rng = pd.date_range('1/1/2012', periods=100, freq='S')
rng # index, time by seconds
ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng)
ts # values (recorded every second)
# resampling: 100 sec = 1 min and 40 sec
ts.resample('5Min').sum() # resample into 5 min data
ts.resample('1Min').sum()
ts.resample('20S').mean() # mean values per each 20 sec periods
pd.Series.resample?
# Time zone representation
rng = pd.date_range('3/6/2012 00:00', periods=5, freq='D')
rng
ts = pd.Series(np.random.randn(len(rng)), rng)
ts
ts_utc = ts.tz_localize('UTC')
ts_utc
# Convert to another time zone
ts_utc.tz_convert('US/Eastern')
# time stamp vs time span
# Converting between time span representations
rng = pd.date_range('1/1/2012', periods=5, freq='M') # time stamp representation
rng # months represented as the last days of each of the 5 months
pd.date_range('1/2012', periods=5, freq='M') # the same
pd.date_range('2012', periods=5, freq='M') # the same
rng.to_period() # time span representation
ts = pd.Series(np.random.randn(len(rng)), index=rng)
ts
ps = ts.to_period()
ps # months represented as months, date & time info lost
ps.to_timestamp() # now months represented as the first day of the month
''' Converting between period and timestamp
enables some convenient arithmetic functions to be used.
In the following example,
we convert a quarterly frequency with year ending in November
to 9am of the end of the month following the quarter end:'''
# using date_range
pd.date_range('1990Q1','2000Q4', freq='Q') # dates: the last days of each period (quater), Q=Q-DEC by default
pd.date_range('1990Q1','2000Q4', freq='Q-Dec') # the same, this is the default meaning for Q
pd.date_range('1990Q1','2000Q4', freq='Q-Mar') # the same but Q=Q-MAR
pd.date_range('1990Q1','2000Q4', freq='Q-Jun') # the same but Q=Q-JUN
pd.date_range('1990Q1','2000Q4', freq='Q-Sep') # the same but Q=Q-SEP
pd.date_range('1990Q1','2000Q4', freq='Q-Nov') # shifted, the 1st Q of a year is Dec-Feb, Q=Q-NOV
pd.date_range('1990Q1','2000Q4', freq='Q-Feb') # the same but Q=Q-FEB
# using period_range
prng = pd.period_range('1990Q1', '2000Q4', freq='Q-NOV')
prng # periods (quaters)
# converting
prng.asfreq('M') # months: the last month each period (one month for each quater in the range)
prng.asfreq('M', 'e') # the same
prng.asfreq('M', 'e') + 1 # moving by one month forward
(prng.asfreq('M', 'e') + 1).asfreq('D') # days: the last day of the last month+1 of each period
(prng.asfreq('M', 'e') + 1).asfreq('H')
# hours: the last hour, of the the last day of the last month+1 of each period
(prng.asfreq('M', 'e') + 1).asfreq('H', 's')
# time: 00am the first day of the following month - why???
(prng.asfreq('M') + 1).asfreq('H','s') # ditto
(prng.asfreq('M', 'e') + 1).asfreq('H', 's') + 9
# time: 9am the first day of the following month
ts = pd.Series(np.random.random(len(prng)),prng) # time series
ts
ts.index = (prng.asfreq('M', 'e') + 1).asfreq('H', 's') + 9
ts
# categoricals
df = pd.DataFrame({"id":[1,2,3,4,5,6], "raw_grade":['a', 'b', 'b', 'a', 'a', 'e']})
df
df.index
df.columns
df.values
df.describe
# checking column types
df.dtypes
df.columns.to_series().groupby(df.dtypes).groups # list of columns of a certain type
df.columns.groupby(df.dtypes) # the same shorter
# convert into categorical type
df["grade"] = df["raw_grade"].astype("category")
df["grade"] # see 3 categories
df
df.dtypes
df.values
df.columns.groupby(df.dtypes)
# Rename the categories to more meaningful names
df.grade.cat?
df.grade.cat.categories # Index(['a', 'b', 'e'], dtype='object')
df["grade"].cat.categories = ["very good", "good", "very bad"]
df.grade.cat.categories # Index(['very good', 'good', 'very bad'], dtype='object')
df
# Reorder the categories and simultaneously add the missing categories
# (methods under Series .cat return a new Series per default - but you can use "inplace")
df["grade"] = df["grade"].cat.set_categories(["very bad", "bad", "medium", "good", "very good"])
df.grade.cat.categories # Index(['very bad', 'bad', 'medium', 'good', 'very good'], dtype='object')
df
df.grade # see 5 categories
# Sorting: per order in the categories, not lexical order
df.sort_values(by="grade")
df.sort_values(by="grade", ascending=False)
# df.sort('grade', ascending=False) # deprecated
# Grouping by a categorical column shows also empty categories.
df.groupby('grade').size() # all
df.groupby('grade').groups # non empty only
################# PLOTTING ####################################
# Plotting Series
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) # default freq is a day here
ts.head()
ts.tail()
ts2 = ts.cumsum()
ts.plot() # random noise
ts2.plot() # random walk
# If the index consists of dates, it calls gcf().autofmt_xdate() to try to format the x-axis
# Plotting Data Frames
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.randn(1000,4), index=ts.index, columns=['A','B','C','D'])
df.head() # random noise
df.tail()
df2 = df.cumsum() # random walk
plt.figure();df2.plot();plt.legend(loc='best')
df2.plot() # the same
###############################################################
# Getting Data In/Out
import os
tmp = os.getcwd()
tmp
tmp #= 'D:\\data\\Dropbox\\workarea\\python-work'
directory = 'D:\\data\\Dropbox\\workarea\\python-work\\Tutorials\\data'
if not os.path.exists(directory):
os.makedirs(directory)
if os.getcwd() != directory:
os.chdir(directory)
os.getcwd()
# CSV
df2.to_csv('foo.csv')
df3 = pd.read_csv('foo.csv')
# compare the two data frames (before and after CSV)
df2.head()
df3.head()
# two differences, df3 has:
# - new index column (1,2,3,...)
# - the old index as the 'Unnamed:0' column
# fixing this:
df4 = pd.read_csv('foo.csv', index_col=0)
df4.head() # great!
# HDF5
df2.to_hdf('foo.h5','df')
(pd.read_hdf('foo.h5','df')).head() # very nice!
# XLSX
df2.to_excel('foo.xlsx', sheet_name='Sheet1')
(pd.read_excel('foo.xlsx', 'Sheet1', index_col=None, na_values=['NA'])).head()
os.chdir(tmp)
################################################################
#######################################################################################
#######################################################################################
''' 100 Panadas '''
import numpy as np
import pandas as pd
pd.__version__
pd.show_versions()
data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],
'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],
'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
data # columns with labels and values
labels # row labels
# 4
df = pd.DataFrame(data, labels) # 'columns' not needed as data is a dictionary and provides colnames
df
# 5
df.describe
df.info
# 6
df.iloc[:3]
df[:3]
df['a':'c']
df[:'c']
df.loc[:'c']
df.ix[:3]
df.head(3)
# 7
df[['age','animal']]
df.loc[['age','animal']] # error
df.loc[:,['age','animal']] # ok
df[[0,1]] # ok
df.iloc[:,[0,1]]
df.ix[:,['age','animal']]
df.ix[:,[0,1]]
# 8
rows=[3,4,8]
cols=['animal','age']
df[cols].iloc[rows]
df.loc[:,cols].iloc[rows]
df.iloc[rows].loc[:,cols]
df.ix[rows,cols] # best
# 9
df[[True,False]*5] # selects rows
df[:,[True,False]*2] # error, you can't select columns this way
df[df.visits>=3]
# 10
df[df.age.isnull()]
# 11
df[(df.animal=='cat') & (df.age<3)]
# 12
df[(df.age>=2) & (df.age<=4)]
# 13
df['age']['f']
df.age['f']
df['age'].f
df.age.f
df.loc['f','age']
df.ix['f','age']
df.age.f = 1.5
# 14
df.visits.sum()
# 15
df.groupby('animal').age.mean()
# 16
x = [1.1,'dog','yes',4]
# attempts
df.append(np.array(x))
# numpy array doesn't work here.
df.append(x)
# wrong: this appends a data series being a new column '0' (so 4 new rows, 1 new column)
df.append([x])
# better, but still wrong: a new row appended but index and columns have to be set.
# you need to append a data frame
pd.DataFrame([x], ['k'], df.columns)
# good!
# solution using append function
df = df.append(pd.DataFrame([x], ['k'], df.columns))
df
df = df.drop('k')
df
# solution using .loc
df.loc['k'] = x
df = df.drop('k')
# 17
df.groupby('animal').count() # too much data (shows how many non-nan values there are)
df.animal.count() # that's too little
df.animal.value_counts() # good!
# 18
df.sort_values(['age','visits'], ascending=[False,True])
# 19
# simple
df.priority = (df.priority=='yes') # very simple!
df.priority.dtype # this is bool
# official
df.priority = df.priority.map({'yes':True, 'no': False})
# 20
# simple
df.animal[df.animal=='snake'] = 'python'
# official
df.animal.replace('snake','python', inplace=True)
# 21
# For each animal type and each number of visits, find the mean age.
# In other words, each row is an animal, each column is a number of visits and the values are the mean ages
df.pivot_table('age','animal','visits') # aggfunc = np.mean, by default
# 22
# a DataFrame df with a column 'A' of integers
df = pd.DataFrame({'A': [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7]})
# How do you filter out rows which contain the same integer as the row immediately above
# rows which contain the same integer as the row immediately above
df[1:].values==df[:-1].values # you have to use '.values' as indeces don't match
df[df[1:].values==df[:-1].values] # Error, drop the last row or add False at the end
# adding False at the end
np.append(df[1:].values==df[:-1].values, np.array([[False]]), axis=0)
np.append(df[1:].values==df[:-1].values, False)[:,None]
# dropping the last row
df[:-1][df[1:].values==df[:-1].values]
# official solution
df.A.shift()
df.A.shift() == df.A
df[df.A.shift() == df.A]
# another one
df.shift() == df
df[(df.shift() == df).values]
# filter out rows which contain the same integer as the row immediately above
df[df.A.shift() != df.A]
# 23
# Given a DataFrame of numeric values
df = pd.DataFrame(np.random.random(size=(5, 3)))
# how do you subtract the row mean from each element in the row
df
df.mean(axis=1) # row means
df - df.mean(axis=1) # wrong: applied to columns
df.sub(df.mean(axis=1), 'rows') # done
df.sub(df.mean(axis=1), 'rows').mean(axis=1) # checking
# official
df.sub(df.mean(axis=1), axis=0) # the same
# 24
# Suppose you have DataFrame with 10 columns of real numbers, for example:
df = pd.DataFrame(np.random.random(size=(5, 10)), index=list('abcdefghij')) # wrong
df = pd.DataFrame(np.random.random(size=(5, 10)), columns=list('abcdefghij')) # OK
# Which column of numbers has the smallest sum? (Find that column's label.)
df.sum(axis=0).min() # minimal value, but we need index
df.sum(axis=0).idxmin() # no correct
# 25
# How do you count how many unique rows a DataFrame has
# (i.e. ignore all rows that are duplicates)?
x = pd.DataFrame(npr.randint(0,3,(10,2)), columns=list('ab'))
x
x.drop_duplicates() # unique rows
x.drop_duplicates(keep=False) # rows that do not have any duplicates
len(x.drop_duplicates(keep=False)) # just 3 rows without duplicates
# 26
# You have a DataFrame that consists of 10 columns of floating--point numbers.
# Suppose that exactly 5 entries in each row are NaN values.
# For each row of the DataFrame, find the column which contains the third NaN value.
x = pd.DataFrame(npr.randn(12,10), columns=list('abcdefghij'))
x
for i in range(12):
x.iloc[i,npr.choice(range(10), 5, replace=False)] = np.nan
x
# loop solution - integer indexing
for i in range(12):
c = 0
for j in range (10):
if np.isnan(x.iloc[i,j]):
c += 1
if c == 3:
print('Row', i, 'Col', j)
break
# loop solution - label indexing
for i in range(12):
c = 0
for j in list('abcdefghij'):
if np.isnan(x.ix[i,j]):
c += 1
if c == 3:
print('Row', i, 'Col', j)
break
# done, very nice
# official
x.isnull()
x.isnull().cumsum(axis=1) # operation within columns, preserving rows
(x.isnull().cumsum(axis=1) == 3) # True indicates the correct spots
(x.isnull().cumsum(axis=1) == 3).idxmax(axis=1) # indeces (of columns) that have the 3rd value
# 27
# A DataFrame has a column of groups 'grps' and and column of numbers 'vals'.
# For example:
df = pd.DataFrame({'grps': list('aaabbcaabcccbbc'),
'vals': [12,345,3,1,45,14,4,52,54,23,235,21,57,3,87]})
# For each group, find the sum of the three greatest values.
df
df.groupby('grps').groups
pd.Series([1,3,2,4,6,5,6,6]).nlargest(3) # test
df.groupby('grps').nlargest(3) # failed
df.groupby('grps').apply(pd.Series.nlargest) # error
df.groupby('grps').apply(np.partition, 0) # failed
df.groupby('grps').apply(np.sort) # failed
df.groupby('grps')['vals'].nlargest(3) # finally got the right numbers
df.groupby('grps')['vals'].nlargest(3).sum() # sum accross groups
df.groupby('grps')['vals'].nlargest(3).sum(level=0) # sum for each group, done!
df.groupby('grps')['vals'].nlargest(3).sum(level=1) # wrong level
df.groupby('grps')['vals'].nlargest(3).unstack() # default = last level = 1
df.groupby('grps')['vals'].nlargest(3).unstack().sum(axis=1) # the same, done!
df.groupby('grps')['vals'].nlargest(3).unstack(level=0) # groups became columns
df.groupby('grps')['vals'].nlargest(3).unstack(level=0).sum() # correct
df.pivot_table('vals','grps', aggfunc='sum') # this sums up all values, not a solution
# 28
# A DataFrame has two integer columns 'A' and 'B'. The values in 'A' are between 1 and 100 (inclusive).
# For each group of 10 consecutive integers in 'A' (i.e. (0, 10], (10, 20], ...),
# calculate the sum of the corresponding values in column 'B'.
# checking
df = pd.DataFrame({'A': np.random.randint(1,101,100),
'B': np.random.randint(1,11,100)})
df.head()
# official
df.groupby(pd.cut(df['A'], np.arange(0, 101, 10)))['B'].sum()
# checking
pd.cut?
x = np.random.randint(1,101,100)
x
bins = np.arange(0,101,10)
bins
y = pd.cut(x, bins)
y
y.head() # error
y[0]
y[:1]
y[:2] # ok, so it's a table of labels, each indicating a range that the original x value falls into
y.isnull() # every x got a category, good
pd.cut(df['A'], np.arange(0, 101, 10)) # a Series of labels (label = a range) that can be used just like a column
df.groupby(pd.cut(df['A'], np.arange(0, 101, 10))).groups # grouping by the new labels
# values represents indeces of rows grouped by the labels.
df.groupby(pd.cut(df['A'], np.arange(0, 101, 10)))['B'].sum() # sums of column B values, grouped by the new labels
df.B.groupby(pd.cut(df['A'], np.arange(0, 101, 10))).sum() # the same
df.B.groupby(pd.cut(df.A, np.arange(0, 101, 10))).sum() # the same
# 29
# Consider a DataFrame df where there is an integer column 'X':
df = pd.DataFrame({'X': [7, 2, 0, 3, 4, 2, 5, 0, 3, 4]})
# For each value, count the difference back to the previous zero
# (or the start of the Series, whichever is closer).
# These values should therefore be [1, 2, 0, 1, 2, 3, 4, 0, 1, 2].
# Make this a new column 'Y'.
# loop solution
df.shape
n = df.shape[0]
j=1
for i in range(n):
if df.iloc[i,0]==0:
j=0
print(j)
j+=1
# Y column
df['Y'] = 0
j=1
for i in range(n):
if df.iloc[i,0]==0:
j=0
df.ix[i,'Y'] = j
j+=1
df
df = df.drop('Y', axis=1)
# Vector solution
np.cumsum(df.X!=0) # not that easy...
# official solution 1
# it is really clever (and pure Numpy)
izero = np.r_[-1, (df['X'] == 0).nonzero()[0]] # indices of zeros
idx = np.arange(len(df)) # index for the array
df['Y'] = idx - izero[np.searchsorted(izero - 1, idx) - 1]
# checking
df.X == 0 # True if == 0
(df.X==0).nonzero() # array of indeces of positions with 0 (but inside a tuple)
(df['X'] == 0).nonzero()[0] # ditto but clean
np.r_[-1, (df['X'] == 0).nonzero()[0]] # ditto but -1 added at the beginning
izero = np.r_[-1, (df['X'] == 0).nonzero()[0]]
#
?np.searchsorted # indices where elements should be inserted to maintain order
idx = np.arange(len(df)) # index for the array
izero-1
idx
np.searchsorted(izero - 1, idx) # Array of insertion points
np.array(df.X)
# -> this is inserting idx into izero array
# so it groups elements laying between the zeros (including the leading zeros)
# so 1 (series 1), 2 (series 2), 3 (series 3)
# so these are values replaced with position (+1) of their leading zero in izero array
np.searchsorted(izero - 1, idx) - 1
# -> ditto but shifted to (0,1,2) from (1,2,3)
izero[np.searchsorted(izero - 1, idx) - 1]
# -> the values are replaced with positions (indeces) of their leading zeros (ie. -1, 2, 7)
idx - izero[np.searchsorted(izero - 1, idx) - 1]
# -> here just deducting the leading zeros positions - done
# it gives positions relative to the leading zero for each series
# official solution 2
# this is also clever
x = (df['X'] != 0).cumsum()
y = x != x.shift()
df['Y'] = y.groupby((y != y.shift()).cumsum()).cumsum()
# checking
df['X'] != 0
x = (df['X'] != 0).cumsum()
x
y = x != x.shift()
y
y != y.shift()
(y != y.shift()).cumsum()
y.groupby((y != y.shift()).cumsum()).groups
y.groupby((y != y.shift()).cumsum()).cumsum()
# 30
# Consider a DataFrame containing rows and columns of purely numerical data.
# Create a list of the row-column index locations of the 3 largest values.
x = np.random.randint(0,20,(4,5))
df = pd.DataFrame(x, columns=list('abcde'))
df
df.idxmax() # max per column
# solution
df.unstack().sort_values(ascending=False)[:3].index.tolist()
# official solution
df.unstack().sort_values()[-3:].index.tolist()
# checking
df
df.unstack()
df.unstack().sort_values()
df.unstack().sort_values()[-3:]
df.unstack().sort_values()[-3:].index
df.unstack().sort_values()[-3:].index.tolist()
# 31
# Given a DataFrame with a column of group IDs, 'grps',
# and a column of corresponding integer values, 'vals',
# replace any negative values in 'vals' with the group mean.
df = pd.DataFrame({'grps':np.random.choice(list('abcd'),10),
'vals':np.random.randint(-50,50,10)})
df
df[df.vals>=0].groupby('grps').vals.mean()
# solution 1: mean of the positive values only
df.ix[df.vals<0,'vals'] = np.nan
tmp1 = df.groupby('grps').apply(lambda x: x.fillna(np.mean(x))) # inplace=True doesn't work here
tmp1
# -> the result is a hierarchical Data Frame
# constructed from stacked series, each serie for one group
# You need to unstack it and preserve just the number index
# dropping the unneeded level in the index:
# method 1:
df['vals'] = tmp1.reset_index(0, drop=True).vals
df
# method 2 and 3 (instead of method 1)
tmp1.index = tmp1.index.get_level_values(1)
tmp1.index = tmp1.index.droplevel(0) # index is not sorted but it's not a problem
df['vals'] = tmp1.vals # assignement is correct per indexing
df
# solution 2: ditto
df.ix[df.vals<0,'vals'] = np.nan
data = df.groupby('grps').vals # SeriesGroupBy
data.size()
data.count()
tmp2 = data.transform(lambda x: x.fillna(np.mean(x)))
tmp2
# -> here you get a Series, that you can substiture for a column in your data frame
df['vals'] = tmp2 # index is sorted, all fits well
df
# Extra:
# tmp2 = data.transform(lambda x: 0 if np.all(pd.isnull(x)) else x.fillna(np.mean(x)))
# -> in case only negative values: 0 on NaN?
# official solution: ditto
def replace(group):
mask = group<0
group[mask] = group[~mask].mean()
return group
df.groupby(['grps'])['vals'].transform(replace)
# checking
df.groupby(['grps'])['vals'].groups
def replace(group):
print(type(group)) # Series
print(group)
j=0
for i in group:
print(j, type(i), i) # int, Series, 0..n
j+=1
return group
df.groupby(['grps'])['vals'].transform(replace)
# short versions:
df = pd.DataFrame({'grps':np.random.choice(list('abcd'),10),
'vals':np.random.randint(-50,50,10)})
dfcopy = df.copy()
df
df[df.vals>=0].groupby('grps').vals.mean()
# 1
df.ix[df.vals<0,'vals'] = np.nan
df.groupby('grps').apply(lambda x: x.fillna(np.mean(x))).reset_index(0, drop=True).vals
# 2
df.ix[df.vals<0,'vals'] = np.nan
df.groupby('grps').vals.transform(lambda x: x.fillna(np.mean(x)))
# 32
# Implement a rolling mean over groups with window size 3, which ignores NaN
# value. For example consider the following DataFrame:
df = pd.DataFrame({'group': list('aabbabbbabab'),
'value': [1, 2, 3, np.nan, 2, 3,np.nan, 1, 7, 3, np.nan, 8]})
df
# The idea is to sum the values in the window (using sum), count the NaN
# values (using count) and then divide to find the mean.
g1 = df.groupby('group').value # group values
g1.groups
g2 = df.fillna(0).groupby('group').value # fillna, then group values
g2.groups
g2.value_counts() # it has NaN's replaced with 0
g2.head
df.ix[g2.groups['a']] # but ...df is still filled with NaNs
df.ix[g2.groups['b']]
df # NaNs are still present
s = g2.rolling(3, min_periods=1).sum() / g1.rolling(3, min_periods=1).count() # compute means
s
s.reset_index(level=0, drop=True).sort_index() # drop/sort index
# checking
df.groupby('group').value.rolling(3,1).count()
df.fillna(0).groupby('group').value.rolling(3,1).sum()
# -> if not minimal windows=1, then NaN's introduced
df.fillna(0).groupby('group').value.rolling(3,1).sum() / \
df.groupby('group').value.rolling(3,1).count()
"""
Series and DatetimeIndex
"""
# 33
# Create a DatetimeIndex that contains each business day of 2015 and use it
# to index a Series of random numbers. Let's call this Series s.
index = pd.date_range('2015','2016', freq='B')[:-1] # business day frequency