/
ops.py
2059 lines (1515 loc) · 61.9 KB
/
ops.py
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
"""
Miscellaneous operations.
"""
import ast
import collections.abc
import copy
import datetime
import html.parser
import inspect
import itertools
import json
import math
import os
import random
import re
import shutil
import socket
import sys
import urllib.parse
import urllib.request
import numpy as np
import pandas as pd
import pkg_resources
import requests
import requests.adapters
import scipy.sparse
import urllib3.util.retry
import pyhelpers._cache
""" == General use =========================================================================== """
def confirmed(prompt=None, confirmation_required=True, resp=False):
"""
Type to confirm whether to proceed or not.
See also [`OPS-C-1 <https://code.activestate.com/recipes/541096/>`_].
:param prompt: a message that prompts a response (Yes/No), defaults to ``None``
:type prompt: str or None
:param confirmation_required: whether to require users to confirm and proceed, defaults to ``True``
:type confirmation_required: bool
:param resp: default response, defaults to ``False``
:type resp: bool
:return: a response
:rtype: bool
**Example**::
>>> from pyhelpers.ops import confirmed
>>> if confirmed(prompt="Testing if the function works?", resp=True):
... print("Passed.")
Testing if the function works? [Yes]|No: yes
Passed.
"""
if confirmation_required:
if prompt is None:
prompt_ = "Confirmed? "
else:
prompt_ = copy.copy(prompt)
if resp is True: # meaning that default response is True
prompt_ = "{} [{}]|{}: ".format(prompt_, "Yes", "No")
else:
prompt_ = "{} [{}]|{}: ".format(prompt_, "No", "Yes")
ans = input(prompt_)
if not ans:
return resp
if re.match('[Yy](es)?', ans):
return True
if re.match('[Nn](o)?', ans):
return False
else:
return True
def get_obj_attr(obj, col_names=None):
"""
Get main attributes of an object.
:param obj: an object, e.g. a class
:type obj: object
:param col_names: a list of column names
:type col_names: list
:return: tabular data of the main attributes of the given object
:rtype: pandas.DataFrame
**Examples**::
>>> from pyhelpers.ops import get_obj_attr
>>> from pyhelpers.dbms import PostgreSQL
>>> postgres = PostgreSQL()
Password (postgres@localhost:5432): ***
Connecting postgres:***@localhost:5432/postgres ... Successfully.
>>> obj_attr = get_obj_attr(postgres)
>>> obj_attr.head()
Attribute Value
0 DEFAULT_DATABASE postgres
1 DEFAULT_DIALECT postgresql
2 DEFAULT_DRIVER psycopg2
3 DEFAULT_HOST localhost
4 DEFAULT_PORT 5432
>>> obj_attr.Attribute.to_list()
['DEFAULT_DATABASE',
'DEFAULT_DIALECT',
'DEFAULT_DRIVER',
'DEFAULT_HOST',
'DEFAULT_PORT',
'DEFAULT_SCHEMA',
'DEFAULT_USERNAME',
'address',
'database_info',
'database_name',
'engine',
'host',
'port',
'url',
'username']
"""
if col_names is None:
col_names = ['Attribute', 'Value']
all_attrs = inspect.getmembers(obj, lambda x: not (inspect.isroutine(x)))
attrs = [x for x in all_attrs if not re.match(r'^__?', x[0])]
attrs_tbl = pd.DataFrame(attrs, columns=col_names)
return attrs_tbl
def eval_dtype(str_val):
"""
Convert a string to its intrinsic data type.
:param str_val: a string-type variable
:type str_val: str
:return: converted value
:rtype: any
**Examples**::
>>> from pyhelpers.ops import eval_dtype
>>> val_1 = '1'
>>> origin_val = eval_dtype(val_1)
>>> origin_val
1
>>> val_2 = '1.1.1'
>>> origin_val = eval_dtype(val_2)
>>> origin_val
'1.1.1'
"""
try:
val = ast.literal_eval(str_val)
except (ValueError, SyntaxError):
val = str_val
return val
def gps_to_utc(gps_time):
"""
Convert standard GPS time to UTC time.
:param gps_time: standard GPS time
:type gps_time: float
:return: UTC time
:rtype: datetime.datetime
**Example**::
>>> from pyhelpers.ops import gps_to_utc
>>> utc_dt = gps_to_utc(gps_time=1271398985.7822514)
>>> utc_dt
datetime.datetime(2020, 4, 20, 6, 23, 5, 782251)
"""
gps_from_utc = (datetime.datetime(1980, 1, 6) - datetime.datetime(1970, 1, 1)).total_seconds()
utc_time = datetime.datetime.utcfromtimestamp(gps_time + gps_from_utc)
return utc_time
def parse_size(size, binary=True, precision=1):
"""
Parse size from / into readable format of bytes.
:param size: human- or machine-readable format of size
:type size: str or int or float
:param binary: whether to use binary (i.e. factorized by 1024) representation, defaults to ``True``;
if ``binary=False``, use the decimal (or metric) representation (i.e. factorized by 10 ** 3)
:type binary: bool
:param precision: number of decimal places (when converting ``size`` to human-readable format),
defaults to ``1``
:type precision: int
:return: parsed size
:rtype: int or str
**Examples**::
>>> from pyhelpers.ops import parse_size
>>> parse_size(size='123.45 MB')
129446707
>>> parse_size(size='123.45 MB', binary=False)
123450000
>>> parse_size(size='123.45 MiB', binary=True)
129446707
>>> # If a metric unit (e.g. 'MiB') is specified in the input,
>>> # the function returns a result accordingly, no matter whether `binary` is True or False
>>> parse_size(size='123.45 MiB', binary=False)
129446707
>>> parse_size(size=129446707, precision=2)
'123.45 MiB'
>>> parse_size(size=129446707, binary=False, precision=2)
'129.45 MB'
"""
min_unit, units_prefixes = 'B', ['K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
if binary is True: # Binary system
factor, units = 2 ** 10, [x + 'i' + min_unit for x in units_prefixes]
else: # Decimal (or metric) system
factor, units = 10 ** 3, [x + min_unit for x in units_prefixes]
if isinstance(size, str):
val, sym = [x.strip() for x in size.split()]
if re.match(r'.*i[Bb]', sym):
factor, units = 2 ** 10, [x + 'i' + min_unit for x in units_prefixes]
unit = [s for s in units if s[0] == sym[0].upper()][0]
unit_dict = dict(zip(units, [factor ** i for i in range(1, len(units) + 1)]))
parsed_size = int(float(val) * unit_dict[unit]) # in byte
else:
is_negative = size < 0
temp_size, parsed_size = map(copy.copy, (abs(size), size))
for unit in [min_unit] + units:
if abs(temp_size) < factor:
parsed_size = f"{'-' if is_negative else ''}{temp_size:.{precision}f} {unit}"
break
if unit != units[-1]:
temp_size /= factor
return parsed_size
def get_number_of_chunks(file_or_obj, chunk_size_limit=50, binary=True):
"""
Get total number of chunks of a data file, given a minimum limit of chunk size.
:param file_or_obj: absolute path to a file
:type file_or_obj: str
:param chunk_size_limit: the minimum limit of file size (in mebibyte i.e. MiB, or megabyte, i.e. MB)
above which the function counts how many chunks there could be, defaults to ``50``;
:type chunk_size_limit: int
:param binary: whether to use binary (i.e. factorized by 1024) representation, defaults to ``True``;
if ``binary=False``, use the decimal (or metric) representation (i.e. factorized by 10 ** 3)
:type binary: bool
:return: number of chunks
:rtype: int or None
**Examples**::
>>> from pyhelpers.ops import get_number_of_chunks
>>> import os
>>> file_path = "C:\\Program Files\\Python39\\python39.pdb"
>>> os.path.getsize(file_path)
13611008
>>> get_number_of_chunks(file_path, chunk_size_limit=2)
7
"""
factor = 2 ** 10 if binary is True else 10 ** 3
if isinstance(file_or_obj, str) and os.path.exists(file_or_obj):
size = os.path.getsize(file_or_obj)
else:
size = sys.getsizeof(file_or_obj)
file_size_in_mb = round(size / (factor ** 2), 1)
if chunk_size_limit and file_size_in_mb > chunk_size_limit:
number_of_chunks = math.ceil(file_size_in_mb / chunk_size_limit)
else:
number_of_chunks = None
return number_of_chunks
def find_executable(app_name, possibilities=None):
"""
Get pathname of an executable file for a specified application.
:param app_name: executable filename of the application that is to be called
:type app_name: str
:param possibilities: possible pathnames
:type possibilities: list or None
:return: pathname of the executable file
:rtype: str
**Examples**::
>>> from pyhelpers.ops import find_executable
>>> import os
>>> python_exe = "python.exe"
>>> possible_paths = ["C:\\Program Files\\Python39", "C:\\Python39"]
>>> path_to_python_exe = find_executable(app_name=python_exe, possibilities=possible_paths)
>>> os.path.relpath(path_to_python_exe)
'venv\\Scripts\\python.exe'
>>> text_exe = "pyhelpers.exe" # This file does not actually exist
>>> path_to_test_exe = find_executable(app_name=text_exe, possibilities=possible_paths)
>>> path_to_test_exe
'pyhelpers.exe'
"""
exe = copy.copy(app_name)
if not os.path.isfile(exe):
alt_exe_pathnames = [shutil.which(app_name)]
if possibilities is not None:
alt_exe_pathnames += possibilities
for exe_pathname in alt_exe_pathnames:
if exe_pathname:
if os.path.isfile(exe_pathname):
exe = exe_pathname
break
return exe
""" == Basic data manipulation =============================================================== """
# Iterable
def loop_in_pairs(iterable):
"""
Get every pair (current, next).
:param iterable: iterable object
:type iterable: typing.Iterable
:return: a `zip <https://docs.python.org/3.9/library/functions.html#zip>`_-type variable
:rtype: zip
**Examples**::
>>> from pyhelpers.ops import loop_in_pairs
>>> res = loop_in_pairs(iterable=[1])
>>> list(res)
[]
>>> res = loop_in_pairs(iterable=range(0, 10))
>>> list(res)
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
"""
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b)
def split_list_by_size(lst, sub_len):
"""
Split a list into (evenly sized) sub-lists.
See also [`OPS-SLBS-1 <https://stackoverflow.com/questions/312443/>`_].
:param lst: a list of any
:type lst: list
:param sub_len: length of a sub-list
:type sub_len: int
:return: a sequence of ``sub_len``-sized sub-lists from ``lst``
:rtype: typing.Generator[list]
**Example**::
>>> from pyhelpers.ops import split_list_by_size
>>> lst_ = list(range(0, 10))
>>> lst_
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lists = split_list_by_size(lst_, sub_len=3)
>>> list(lists)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
"""
for i in range(0, len(lst), sub_len):
yield lst[i:i + sub_len]
def split_list(lst, num_of_sub):
"""
Split a list into a number of equally-sized sub-lists.
See also [`OPS-SL-1 <https://stackoverflow.com/questions/312443/>`_].
:param lst: a list of any
:type lst: list
:param num_of_sub: number of sub-lists
:type num_of_sub: int
:return: a total of ``num_of_sub`` sub-lists from ``lst``
:rtype: typing.Generator[list]
**Example**::
>>> from pyhelpers.ops import split_list
>>> lst_ = list(range(0, 10))
>>> lst_
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lists = split_list(lst_, num_of_sub=3)
>>> list(lists)
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]
"""
chunk_size = math.ceil(len(lst) / num_of_sub)
for i in range(0, len(lst), chunk_size):
yield lst[i:i + chunk_size]
def split_iterable(iterable, chunk_size):
"""
Split a list into (evenly sized) chunks.
See also [`OPS-SI-1 <https://stackoverflow.com/questions/24527006/>`_].
:param iterable: iterable object
:type iterable: typing.Iterable
:param chunk_size: length of a chunk
:type chunk_size: int
:return: a sequence of equally-sized chunks from ``iterable``
:rtype: typing.Generator[typing.Iterable]
**Examples**::
>>> from pyhelpers.ops import split_iterable
>>> import pandas
>>> iterable_1 = list(range(0, 10))
>>> iterable_1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> iterable_1_ = split_iterable(iterable_1, chunk_size=3)
>>> type(iterable_1_)
generator
>>> for dat in iterable_1_:
... print(list(dat))
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9]
>>> iterable_2 = pandas.Series(range(0, 20))
>>> iterable_2
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
11 11
12 12
13 13
14 14
15 15
16 16
17 17
18 18
19 19
dtype: int64
>>> iterable_2_ = split_iterable(iterable_2, chunk_size=5)
>>> for dat in iterable_2_:
... print(list(dat))
[0, 1, 2, 3, 4]
[5, 6, 7, 8, 9]
[10, 11, 12, 13, 14]
[15, 16, 17, 18, 19]
"""
iterator = iter(iterable)
for x in iterator:
yield itertools.chain([x], itertools.islice(iterator, chunk_size - 1))
def update_dict(dictionary, updates, inplace=False):
"""
Update a (nested) dictionary or similar mapping.
See also [`OPS-UD-1 <https://stackoverflow.com/questions/3232943/>`_].
:param dictionary: a (nested) dictionary that needs to be updated
:type dictionary: dict
:param updates: a dictionary with new data
:type updates: dict
:param inplace: whether to replace the original ``dictionary`` with the updated one,
defaults to ``False``
:type inplace: bool
:return: an updated dictionary
:rtype: dict
**Examples**::
>>> from pyhelpers.ops import update_dict
>>> source_dict = {'key_1': 1}
>>> update_data = {'key_2': 2}
>>> upd_dict = update_dict(source_dict, updates=update_data)
>>> upd_dict
{'key_1': 1, 'key_2': 2}
>>> source_dict
{'key_1': 1}
>>> update_dict(source_dict, updates=update_data, inplace=True)
>>> source_dict
{'key_1': 1, 'key_2': 2}
>>> source_dict = {'key': 'val_old'}
>>> update_data = {'key': 'val_new'}
>>> upd_dict = update_dict(source_dict, updates=update_data)
>>> upd_dict
{'key': 'val_new'}
>>> source_dict = {'key': {'k1': 'v1_old', 'k2': 'v2'}}
>>> update_data = {'key': {'k1': 'v1_new'}}
>>> upd_dict = update_dict(source_dict, updates=update_data)
>>> upd_dict
{'key': {'k1': 'v1_new', 'k2': 'v2'}}
>>> source_dict = {'key': {'k1': {}, 'k2': 'v2'}}
>>> update_data = {'key': {'k1': 'v1'}}
>>> upd_dict = update_dict(source_dict, updates=update_data)
>>> upd_dict
{'key': {'k1': 'v1', 'k2': 'v2'}}
>>> source_dict = {'key': {'k1': 'v1', 'k2': 'v2'}}
>>> update_data = {'key': {'k1': {}}}
>>> upd_dict = update_dict(source_dict, updates=update_data)
>>> upd_dict
{'key': {'k1': 'v1', 'k2': 'v2'}}
"""
if inplace:
updated_dict = dictionary
else:
updated_dict = copy.copy(dictionary)
for key, val in updates.items():
if isinstance(val, collections.abc.Mapping) or isinstance(val, dict):
updated_dict[key] = update_dict(dictionary.get(key, {}), val)
elif isinstance(val, list):
updated_dict[key] = (updated_dict.get(key, []) + val)
else:
updated_dict[key] = updates[key]
if not inplace:
return updated_dict
def update_dict_keys(dictionary, replacements=None):
"""
Update keys in a (nested) dictionary.
See also
[`OPS-UDK-1 <https://stackoverflow.com/questions/4406501/>`_] and
[`OPS-UDK-2 <https://stackoverflow.com/questions/38491318/>`_].
:param dictionary: a (nested) dictionary in which certain keys are to be updated
:type dictionary: dict
:param replacements: a dictionary in the form of ``{<current_key>: <new_key>}``,
describing which keys are to be updated, defaults to ``None``
:type replacements: dict or None
:return: an updated dictionary
:rtype: dict
**Examples**::
>>> from pyhelpers.ops import update_dict_keys
>>> source_dict = {'a': 1, 'b': 2, 'c': 3}
>>> upd_dict = update_dict_keys(source_dict, replacements=None)
>>> upd_dict # remain unchanged
{'a': 1, 'b': 2, 'c': 3}
>>> repl_keys = {'a': 'd', 'c': 'e'}
>>> upd_dict = update_dict_keys(source_dict, replacements=repl_keys)
>>> upd_dict
{'d': 1, 'b': 2, 'e': 3}
>>> source_dict = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': {'f': 4, 'g': 5}}}
>>> repl_keys = {'d': 3, 'f': 4}
>>> upd_dict = update_dict_keys(source_dict, replacements=repl_keys)
>>> upd_dict
{'a': 1, 'b': 2, 'c': {3: 3, 'e': {4: 4, 'g': 5}}}
"""
if replacements is None:
updated_dict = dictionary.copy()
else:
updated_dict = {}
if isinstance(dictionary, list):
updated_dict = list()
for x in dictionary:
updated_dict.append(update_dict_keys(x, replacements))
else:
for k in dictionary.keys():
v = dictionary[k]
k_ = replacements.get(k, k)
if isinstance(v, (dict, list)):
updated_dict[k_] = update_dict_keys(v, replacements)
else:
updated_dict[k_] = v
return updated_dict
def get_dict_values(key, dictionary):
"""
Get all values in a (nested) dictionary for a given key.
See also
[`OPS-GDV-1 <https://gist.github.com/douglasmiranda/5127251>`_] and
[`OPS-GDV-2 <https://stackoverflow.com/questions/9807634/>`_].
:param key: any that can be the key of a dictionary
:type key: any
:param dictionary: a (nested) dictionary
:type dictionary: dict
:return: all values of the ``key`` within the given ``target_dict``
:rtype: typing.Generator[typing.Iterable]
**Examples**::
>>> from pyhelpers.ops import get_dict_values
>>> key_ = 'key'
>>> target_dict_ = {'key': 'val'}
>>> val = get_dict_values(key_, target_dict_)
>>> list(val)
[['val']]
>>> key_ = 'k1'
>>> target_dict_ = {'key': {'k1': 'v1', 'k2': 'v2'}}
>>> val = get_dict_values(key_, target_dict_)
>>> list(val)
[['v1']]
>>> key_ = 'k1'
>>> target_dict_ = {'key': {'k1': ['v1', 'v1_1']}}
>>> val = get_dict_values(key_, target_dict_)
>>> list(val)
[['v1', 'v1_1']]
>>> key_ = 'k2'
>>> target_dict_ = {'key': {'k1': 'v1', 'k2': ['v2', 'v2_1']}}
>>> val = get_dict_values(key_, target_dict_)
>>> list(val)
[['v2', 'v2_1']]
"""
for k, v in dictionary.items():
if key == k:
yield [v] if isinstance(v, str) else v
elif isinstance(v, dict):
for x in get_dict_values(key, v):
yield x
elif isinstance(v, collections.abc.Iterable):
for d in v:
if isinstance(d, dict):
for y in get_dict_values(key, d):
yield y
def remove_dict_keys(dictionary, *keys):
"""
Remove multiple keys from a dictionary.
:param dictionary: a dictionary
:type dictionary: dict
:param keys: (a sequence of) any that can be the key of a dictionary
:type keys: any
**Example**::
>>> from pyhelpers.ops import remove_dict_keys
>>> target_dict_ = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3', 'k4': 'v4', 'k5': 'v5'}
>>> remove_dict_keys(target_dict_, 'k1', 'k3', 'k4')
>>> target_dict_
{'k2': 'v2', 'k5': 'v5'}
"""
# assert isinstance(dictionary, dict)
for k in keys:
if k in dictionary.keys():
dictionary.pop(k)
def compare_dicts(dict1, dict2):
"""
Compare the difference between two dictionaries.
See also [`OPS-CD-1 <https://stackoverflow.com/questions/23177439>`_].
:param dict1: a dictionary
:type dict1: dict
:param dict2: another dictionary
:type dict2: dict
:return: in comparison to ``dict1``, the main difference on ``dict2``, including:
modified items, keys that are the same, keys where values remain unchanged, new keys and
keys that are removed
:rtype: typing.Tuple[dict, list]
**Examples**::
>>> from pyhelpers.ops import compare_dicts
>>> d1 = {'a': 1, 'b': 2, 'c': 3}
>>> d2 = {'b': 2, 'c': 4, 'd': [5, 6]}
>>> items_modified, k_shared, k_unchanged, k_new, k_removed = compare_dicts(d1, d2)
>>> items_modified
{'c': [3, 4]}
>>> k_shared
['b', 'c']
>>> k_unchanged
['b']
>>> k_new
['d']
>>> k_removed
['a']
"""
dk1, dk2 = map(lambda x: set(x.keys()), (dict1, dict2))
shared_keys = dk1.intersection(dk2)
added_keys, removed_keys = list(dk2 - dk1), list(dk1 - dk2)
modified_items = {k: [dict1[k], dict2[k]] for k in shared_keys if dict1[k] != dict2[k]}
unchanged_keys = list(set(k for k in shared_keys if dict1[k] == dict2[k]))
return modified_items, list(shared_keys), unchanged_keys, added_keys, removed_keys
def merge_dicts(*dicts):
"""
Merge multiple dictionaries.
:param dicts: (one or) multiple dictionaries
:type dicts: dict
:return: a single dictionary containing all elements of the input
:rtype: dict
**Examples**::
>>> from pyhelpers.ops import merge_dicts
>>> dict_a = {'a': 1}
>>> dict_b = {'b': 2}
>>> dict_c = {'c': 3}
>>> merged_dict = merge_dicts(dict_a, dict_b, dict_c)
>>> merged_dict
{'a': 1, 'b': 2, 'c': 3}
>>> dict_c_ = {'c': 4}
>>> merged_dict = merge_dicts(merged_dict, dict_c_)
>>> merged_dict
{'a': 1, 'b': 2, 'c': [3, 4]}
>>> dict_1 = merged_dict
>>> dict_2 = {'b': 2, 'c': 4, 'd': [5, 6]}
>>> merged_dict = merge_dicts(dict_1, dict_2)
{'a': 1, 'b': 2, 'c': [[3, 4], 4], 'd': [5, 6]}
"""
new_dict = {}
for d in dicts:
d_ = d.copy()
# dk1, dk2 = map(lambda x: set(x.keys()), (new_dict, d_))
# modified = {k: [new_dict[k], d_[k]] for k in dk1.intersection(dk2) if new_dict[k] != d_[k]}
modified_items, _, _, _, _, = compare_dicts(new_dict, d_)
if bool(modified_items):
new_dict.update(modified_items)
for k_ in modified_items.keys():
remove_dict_keys(d_, k_)
new_dict.update(d_)
return new_dict
# Tabular data
def detect_nan_for_str_column(data_frame, column_names=None):
"""
Detect if a str type column contains ``NaN`` when reading csv files.
:param data_frame: a data frame to be examined
:type data_frame: pandas.DataFrame
:param column_names: a sequence of column names, if ``None`` (default), all columns
:type column_names: None or collections.abc.Iterable
:return: position index of the column that contains ``NaN``
:rtype: typing.Generator[typing.Iterable]
**Example**::
>>> from pyhelpers.ops import detect_nan_for_str_column
>>> from pyhelpers._cache import example_dataframe
>>> dat = example_dataframe()
>>> dat
Easting Northing
London 530034 180381
Birmingham 406689 286822
Manchester 383819 398052
Leeds 582044 152953
>>> dat.iloc[3, 1] = None
>>> dat
Easting Northing
London 530034 180381.0
Birmingham 406689 286822.0
Manchester 383819 398052.0
Leeds 582044 NaN
>>> nan_col_pos = detect_nan_for_str_column(data_frame=dat, column_names=None)
>>> list(nan_col_pos)
[1]
"""
if column_names is None:
column_names = data_frame.columns
for x in column_names:
temp = [str(v) for v in data_frame[x].unique() if isinstance(v, str) or np.isnan(v)]
if 'nan' in temp:
yield data_frame.columns.get_loc(x)
def create_rotation_matrix(theta):
"""
Create a rotation matrix (counterclockwise).
:param theta: rotation angle (in radian)
:type theta: int or float
:return: a rotation matrix of shape (2, 2)
:rtype: numpy.ndarray
**Example**::
>>> from pyhelpers.ops import create_rotation_matrix
>>> rot_mat = create_rotation_matrix(theta=30)
>>> rot_mat
array([[-0.98803162, 0.15425145],
[-0.15425145, -0.98803162]])
"""
sin_theta, cos_theta = np.sin(theta), np.cos(theta)
rotation_mat = np.array([[sin_theta, cos_theta], [-cos_theta, sin_theta]])
return rotation_mat
def dict_to_dataframe(input_dict, k='key', v='value'):
"""
Convert a dictionary to a data frame.
:param input_dict: a dictionary to be converted to a data frame
:type input_dict: dict
:param k: column name for keys
:type k: str
:param v: column name for values
:type v: str
:return: a data frame converted from the ``input_dict``
:rtype: pandas.DataFrame
**Example**::
>>> from pyhelpers.ops import dict_to_dataframe
>>> test_dict = {'a': 1, 'b': 2}
>>> dat = dict_to_dataframe(input_dict=test_dict)
>>> dat
key value
0 a 1
1 b 2
"""
dict_keys = list(input_dict.keys())
dict_vals = list(input_dict.values())
data_frame = pd.DataFrame({k: dict_keys, v: dict_vals})
return data_frame
def parse_csr_matrix(path_to_csr, verbose=False, **kwargs):
"""
Load in a compressed sparse row (CSR) or compressed row storage (CRS).
:param path_to_csr: path where a CSR file (e.g. with a file extension ".npz") is saved
:type path_to_csr: str
:param verbose: whether to print relevant information in console as the function runs,
defaults to ``False``
:type verbose: bool or int
:param kwargs: [optional] parameters of `numpy.load`_
:return: a compressed sparse row
:rtype: scipy.sparse.csr.csr_matrix
.. _`numpy.load`: https://numpy.org/doc/stable/reference/generated/numpy.load
**Example**::
>>> from pyhelpers.ops import parse_csr_matrix
>>> from pyhelpers.dir import cd
>>> import numpy
>>> import scipy.sparse
>>> data_ = numpy.array([1, 2, 3, 4, 5, 6])
>>> indices_ = numpy.array([0, 2, 2, 0, 1, 2])
>>> indptr_ = numpy.array([0, 2, 3, 6])
>>> csr_m = scipy.sparse.csr_matrix((data_, indices_, indptr_), shape=(3, 3))
>>> csr_m
<3x3 sparse matrix of type '<class 'numpy.int32'>'
with 6 stored elements in Compressed Sparse Row format>
>>> path_to_csr_npz = cd("tests\\data", "csr_mat.npz")
>>> numpy.savez_compressed(path_to_csr_npz, indptr=csr_m.indptr,
... indices=csr_m.indices, data=csr_m.data,
... shape=csr_m.shape)
>>> parsed_csr_mat = parse_csr_matrix(path_to_csr_npz, verbose=True)
Loading "\\tests\\data\\csr_mat.npz" ... Done.
>>> # .nnz gets the count of explicitly-stored values (non-zeros)
>>> (parsed_csr_mat != csr_m).count_nonzero() == 0
True
>>> (parsed_csr_mat != csr_m).nnz == 0
True
"""
if verbose: