-
Notifications
You must be signed in to change notification settings - Fork 884
/
Copy pathentityset.py
1928 lines (1640 loc) · 77.3 KB
/
entityset.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
import copy
import logging
import warnings
from collections import defaultdict
import numpy as np
import pandas as pd
from woodwork import init_series
from woodwork.logical_types import Datetime, LatLong
from featuretools.entityset import deserialize, serialize
from featuretools.entityset.relationship import Relationship, RelationshipPath
from featuretools.feature_base.feature_base import _ES_REF
from featuretools.utils.gen_utils import Library, import_or_none, is_instance
from featuretools.utils.plot_utils import (
check_graphviz,
get_graphviz_format,
save_graph,
)
from featuretools.utils.wrangle import _check_timedelta
dd = import_or_none("dask.dataframe")
ps = import_or_none("pyspark.pandas")
pd.options.mode.chained_assignment = None # default='warn'
logger = logging.getLogger("featuretools.entityset")
LTI_COLUMN_NAME = "_ft_last_time"
WW_SCHEMA_KEY = "_ww__getstate__schemas"
class EntitySet(object):
"""
Stores all actual data and typing information for an entityset
Attributes:
id
dataframe_dict
relationships
time_type
Properties:
metadata
"""
def __init__(self, id=None, dataframes=None, relationships=None):
"""Creates EntitySet
Args:
id (str) : Unique identifier to associate with this instance
dataframes (dict[str -> tuple(DataFrame, str, str, dict[str -> str/Woodwork.LogicalType], dict[str->str/set], boolean)]):
Dictionary of DataFrames. Entries take the format
{dataframe name -> (dataframe, index column, time_index, logical_types, semantic_tags, make_index)}.
Note that only the dataframe is required. If a Woodwork DataFrame is supplied, any other parameters
will be ignored.
relationships (list[(str, str, str, str)]): List of relationships
between dataframes. List items are a tuple with the format
(parent dataframe name, parent column, child dataframe name, child column).
Example:
.. code-block:: python
dataframes = {
"cards" : (card_df, "id"),
"transactions" : (transactions_df, "id", "transaction_time")
}
relationships = [("cards", "id", "transactions", "card_id")]
ft.EntitySet("my-entity-set", dataframes, relationships)
"""
self.id = id
self.dataframe_dict = {}
self.relationships = []
self.time_type = None
dataframes = dataframes or {}
relationships = relationships or []
for df_name in dataframes:
df = dataframes[df_name][0]
if df.ww.schema is not None and df.ww.name != df_name:
raise ValueError(
f"Naming conflict in dataframes dictionary: dictionary key '{df_name}' does not match dataframe name '{df.ww.name}'",
)
index_column = None
time_index = None
make_index = False
semantic_tags = None
logical_types = None
if len(dataframes[df_name]) > 1:
index_column = dataframes[df_name][1]
if len(dataframes[df_name]) > 2:
time_index = dataframes[df_name][2]
if len(dataframes[df_name]) > 3:
logical_types = dataframes[df_name][3]
if len(dataframes[df_name]) > 4:
semantic_tags = dataframes[df_name][4]
if len(dataframes[df_name]) > 5:
make_index = dataframes[df_name][5]
self.add_dataframe(
dataframe_name=df_name,
dataframe=df,
index=index_column,
time_index=time_index,
logical_types=logical_types,
semantic_tags=semantic_tags,
make_index=make_index,
)
for relationship in relationships:
parent_df, parent_column, child_df, child_column = relationship
self.add_relationship(parent_df, parent_column, child_df, child_column)
self.reset_data_description()
_ES_REF[self.id] = self
def __sizeof__(self):
return sum([df.__sizeof__() for df in self.dataframes])
def __dask_tokenize__(self):
return (EntitySet, serialize.entityset_to_description(self.metadata))
def __eq__(self, other, deep=False):
if self.id != other.id:
return False
if self.time_type != other.time_type:
return False
if len(self.dataframe_dict) != len(other.dataframe_dict):
return False
for df_name, df in self.dataframe_dict.items():
if df_name not in other.dataframe_dict:
return False
if not df.ww.__eq__(other[df_name].ww, deep=deep):
return False
if not len(self.relationships) == len(other.relationships):
return False
for r in self.relationships:
if r not in other.relationships:
return False
return True
def __ne__(self, other, deep=False):
return not self.__eq__(other, deep=deep)
def __getitem__(self, dataframe_name):
"""Get dataframe instance from entityset
Args:
dataframe_name (str): Name of dataframe.
Returns:
:class:`.DataFrame` : Instance of dataframe with Woodwork typing information. None if dataframe doesn't
exist on the entityset.
"""
if dataframe_name in self.dataframe_dict:
return self.dataframe_dict[dataframe_name]
name = self.id or "entity set"
raise KeyError("DataFrame %s does not exist in %s" % (dataframe_name, name))
def __deepcopy__(self, memo):
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
if k == "dataframe_dict":
# Copy the DataFrames, retaining Woodwork typing information
copied_attr = copy.copy(v)
for df_name, df in copied_attr.items():
copied_attr[df_name] = df.ww.copy()
else:
copied_attr = copy.deepcopy(v, memo)
setattr(result, k, copied_attr)
for df in result.dataframe_dict.values():
result._add_references_to_metadata(df)
return result
@property
def dataframes(self):
return list(self.dataframe_dict.values())
@property
def dataframe_type(self):
"""String specifying the library used for the dataframes. Null if no dataframes"""
df_type = None
if self.dataframes:
if isinstance(self.dataframes[0], pd.DataFrame):
df_type = Library.PANDAS
elif is_instance(self.dataframes[0], dd, "DataFrame"):
df_type = Library.DASK
elif is_instance(self.dataframes[0], ps, "DataFrame"):
df_type = Library.SPARK
return df_type
@property
def metadata(self):
"""Returns the metadata for this EntitySet. The metadata will be recomputed if it does not exist."""
if self._data_description is None:
description = serialize.entityset_to_description(self)
self._data_description = deserialize.description_to_entityset(description)
return self._data_description
def reset_data_description(self):
self._data_description = None
def to_pickle(self, path, compression=None, profile_name=None):
"""Write entityset in the pickle format, location specified by `path`.
Path could be a local path or a S3 path.
If writing to S3 a tar archive of files will be written.
Args:
path (str): location on disk to write to (will be created as a directory)
compression (str) : Name of the compression to use. Possible values are: {'gzip', 'bz2', 'zip', 'xz', None}.
profile_name (str) : Name of AWS profile to use, False to use an anonymous profile, or None.
"""
serialize.write_data_description(
self,
path,
format="pickle",
compression=compression,
profile_name=profile_name,
)
return self
def to_parquet(self, path, engine="auto", compression=None, profile_name=None):
"""Write entityset to disk in the parquet format, location specified by `path`.
Path could be a local path or a S3 path.
If writing to S3 a tar archive of files will be written.
Args:
path (str): location on disk to write to (will be created as a directory)
engine (str) : Name of the engine to use. Possible values are: {'auto', 'pyarrow'}.
compression (str) : Name of the compression to use. Possible values are: {'snappy', 'gzip', 'brotli', None}.
profile_name (str) : Name of AWS profile to use, False to use an anonymous profile, or None.
"""
serialize.write_data_description(
self,
path,
format="parquet",
engine=engine,
compression=compression,
profile_name=profile_name,
)
return self
def to_csv(
self,
path,
sep=",",
encoding="utf-8",
engine="python",
compression=None,
profile_name=None,
):
"""Write entityset to disk in the csv format, location specified by `path`.
Path could be a local path or a S3 path.
If writing to S3 a tar archive of files will be written.
Args:
path (str) : Location on disk to write to (will be created as a directory)
sep (str) : String of length 1. Field delimiter for the output file.
encoding (str) : A string representing the encoding to use in the output file, defaults to 'utf-8'.
engine (str) : Name of the engine to use. Possible values are: {'c', 'python'}.
compression (str) : Name of the compression to use. Possible values are: {'gzip', 'bz2', 'zip', 'xz', None}.
profile_name (str) : Name of AWS profile to use, False to use an anonymous profile, or None.
"""
if self.dataframe_type == Library.SPARK:
compression = str(compression)
serialize.write_data_description(
self,
path,
format="csv",
index=False,
sep=sep,
encoding=encoding,
engine=engine,
compression=compression,
profile_name=profile_name,
)
return self
def to_dictionary(self):
return serialize.entityset_to_description(self)
###########################################################################
# Public getter/setter methods #########################################
###########################################################################
def __repr__(self):
repr_out = "Entityset: {}\n".format(self.id)
repr_out += " DataFrames:"
for df in self.dataframes:
if df.shape:
repr_out += "\n {} [Rows: {}, Columns: {}]".format(
df.ww.name,
df.shape[0],
df.shape[1],
)
else:
repr_out += "\n {} [Rows: None, Columns: None]".format(df.ww.name)
repr_out += "\n Relationships:"
if len(self.relationships) == 0:
repr_out += "\n No relationships"
for r in self.relationships:
repr_out += "\n %s.%s -> %s.%s" % (
r._child_dataframe_name,
r._child_column_name,
r._parent_dataframe_name,
r._parent_column_name,
)
return repr_out
def add_relationships(self, relationships):
"""Add multiple new relationships to a entityset
Args:
relationships (list[tuple(str, str, str, str)] or list[Relationship]) : List of
new relationships to add. Relationships are specified either as a :class:`.Relationship`
object or a four element tuple identifying the parent and child columns:
(parent_dataframe_name, parent_column_name, child_dataframe_name, child_column_name)
"""
for rel in relationships:
if isinstance(rel, Relationship):
self.add_relationship(relationship=rel)
else:
self.add_relationship(*rel)
return self
def add_relationship(
self,
parent_dataframe_name=None,
parent_column_name=None,
child_dataframe_name=None,
child_column_name=None,
relationship=None,
):
"""Add a new relationship between dataframes in the entityset. Relationships can be specified
by passing dataframe and columns names or by passing a :class:`.Relationship` object.
Args:
parent_dataframe_name (str): Name of the parent dataframe in the EntitySet. Must be specified
if relationship is not.
parent_column_name (str): Name of the parent column. Must be specified if relationship is not.
child_dataframe_name (str): Name of the child dataframe in the EntitySet. Must be specified
if relationship is not.
child_column_name (str): Name of the child column. Must be specified if relationship is not.
relationship (Relationship): Instance of new relationship to be added. Must be specified
if dataframe and column names are not supplied.
"""
if relationship and (
parent_dataframe_name
or parent_column_name
or child_dataframe_name
or child_column_name
):
raise ValueError(
"Cannot specify dataframe and column name values and also supply a Relationship",
)
if not relationship:
relationship = Relationship(
self,
parent_dataframe_name,
parent_column_name,
child_dataframe_name,
child_column_name,
)
if relationship in self.relationships:
warnings.warn("Not adding duplicate relationship: " + str(relationship))
return self
# _operations?
# this is a new pair of dataframes
child_df = relationship.child_dataframe
child_column = relationship._child_column_name
if child_df.ww.index == child_column:
msg = "Unable to add relationship because child column '{}' in '{}' is also its index"
raise ValueError(msg.format(child_column, child_df.ww.name))
parent_df = relationship.parent_dataframe
parent_column = relationship._parent_column_name
if parent_df.ww.index != parent_column:
parent_df.ww.set_index(parent_column)
# Empty dataframes (as a result of accessing metadata)
# default to object dtypes for categorical columns, but
# indexes/foreign keys default to ints. In this case, we convert
# the empty column's type to int
if isinstance(child_df, pd.DataFrame) and (
child_df.empty
and child_df[child_column].dtype == object
and parent_df.ww.columns[parent_column].is_numeric
):
child_df.ww[child_column] = pd.Series(name=child_column, dtype=np.int64)
parent_ltype = parent_df.ww.logical_types[parent_column]
child_ltype = child_df.ww.logical_types[child_column]
if parent_ltype != child_ltype:
difference_msg = ""
if str(parent_ltype) == str(child_ltype):
difference_msg = "There is a conflict between the parameters. "
warnings.warn(
f"Logical type {child_ltype} for child column {child_column} does not match "
f"parent column {parent_column} logical type {parent_ltype}. {difference_msg}"
"Changing child logical type to match parent.",
)
child_df.ww.set_types(logical_types={child_column: parent_ltype})
if "foreign_key" not in child_df.ww.semantic_tags[child_column]:
child_df.ww.add_semantic_tags({child_column: "foreign_key"})
self.relationships.append(relationship)
self.reset_data_description()
return self
def set_secondary_time_index(self, dataframe_name, secondary_time_index):
"""
Set the secondary time index for a dataframe in the EntitySet using its dataframe name.
Args:
dataframe_name (str) : name of the dataframe for which to set the secondary time index.
secondary_time_index (dict[str-> list[str]]): Name of column containing time data to
be used as a secondary time index mapped to a list of the columns in the dataframe
associated with that secondary time index.
"""
dataframe = self[dataframe_name]
self._set_secondary_time_index(dataframe, secondary_time_index)
def _set_secondary_time_index(self, dataframe, secondary_time_index):
"""Sets the secondary time index for a Woodwork dataframe passed in"""
assert (
dataframe.ww.schema is not None
), "Cannot set secondary time index if Woodwork is not initialized"
self._check_secondary_time_index(dataframe, secondary_time_index)
if secondary_time_index is not None:
dataframe.ww.metadata["secondary_time_index"] = secondary_time_index
###########################################################################
# Relationship access/helper methods ###################################
###########################################################################
def find_forward_paths(self, start_dataframe_name, goal_dataframe_name):
"""
Generator which yields all forward paths between a start and goal
dataframe. Does not include paths which contain cycles.
Args:
start_dataframe_name (str) : name of dataframe to start the search from
goal_dataframe_name (str) : name of dataframe to find forward path to
See Also:
:func:`BaseEntitySet.find_backward_paths`
"""
for sub_dataframe_name, path in self._forward_dataframe_paths(
start_dataframe_name,
):
if sub_dataframe_name == goal_dataframe_name:
yield path
def find_backward_paths(self, start_dataframe_name, goal_dataframe_name):
"""
Generator which yields all backward paths between a start and goal
dataframe. Does not include paths which contain cycles.
Args:
start_dataframe_name (str) : Name of dataframe to start the search from.
goal_dataframe_name (str) : Name of dataframe to find backward path to.
See Also:
:func:`BaseEntitySet.find_forward_paths`
"""
for path in self.find_forward_paths(goal_dataframe_name, start_dataframe_name):
# Reverse path
yield path[::-1]
def _forward_dataframe_paths(self, start_dataframe_name, seen_dataframes=None):
"""
Generator which yields the names of all dataframes connected through forward
relationships, and the path taken to each. A dataframe will be yielded
multiple times if there are multiple paths to it.
Implemented using depth first search.
"""
if seen_dataframes is None:
seen_dataframes = set()
if start_dataframe_name in seen_dataframes:
return
seen_dataframes.add(start_dataframe_name)
yield start_dataframe_name, []
for relationship in self.get_forward_relationships(start_dataframe_name):
next_dataframe = relationship._parent_dataframe_name
# Copy seen dataframes for each next node to allow multiple paths (but
# not cycles).
descendants = self._forward_dataframe_paths(
next_dataframe,
seen_dataframes.copy(),
)
for sub_dataframe_name, sub_path in descendants:
yield sub_dataframe_name, [relationship] + sub_path
def get_forward_dataframes(self, dataframe_name, deep=False):
"""
Get dataframes that are in a forward relationship with dataframe
Args:
dataframe_name (str): Name of dataframe to search from.
deep (bool): if True, recursively find forward dataframes.
Yields a tuple of (descendent_name, path from dataframe_name to descendant).
"""
for relationship in self.get_forward_relationships(dataframe_name):
parent_dataframe_name = relationship._parent_dataframe_name
direct_path = RelationshipPath([(True, relationship)])
yield parent_dataframe_name, direct_path
if deep:
sub_dataframes = self.get_forward_dataframes(
parent_dataframe_name,
deep=True,
)
for sub_dataframe_name, path in sub_dataframes:
yield sub_dataframe_name, direct_path + path
def get_backward_dataframes(self, dataframe_name, deep=False):
"""
Get dataframes that are in a backward relationship with dataframe
Args:
dataframe_name (str): Name of dataframe to search from.
deep (bool): if True, recursively find backward dataframes.
Yields a tuple of (descendent_name, path from dataframe_name to descendant).
"""
for relationship in self.get_backward_relationships(dataframe_name):
child_dataframe_name = relationship._child_dataframe_name
direct_path = RelationshipPath([(False, relationship)])
yield child_dataframe_name, direct_path
if deep:
sub_dataframes = self.get_backward_dataframes(
child_dataframe_name,
deep=True,
)
for sub_dataframe_name, path in sub_dataframes:
yield sub_dataframe_name, direct_path + path
def get_forward_relationships(self, dataframe_name):
"""Get relationships where dataframe "dataframe_name" is the child
Args:
dataframe_name (str): Name of dataframe to get relationships for.
Returns:
list[:class:`.Relationship`]: List of forward relationships.
"""
return [
r for r in self.relationships if r._child_dataframe_name == dataframe_name
]
def get_backward_relationships(self, dataframe_name):
"""
get relationships where dataframe "dataframe_name" is the parent.
Args:
dataframe_name (str): Name of dataframe to get relationships for.
Returns:
list[:class:`.Relationship`]: list of backward relationships
"""
return [
r for r in self.relationships if r._parent_dataframe_name == dataframe_name
]
def has_unique_forward_path(self, start_dataframe_name, end_dataframe_name):
"""
Is the forward path from start to end unique?
This will raise if there is no such path.
"""
paths = self.find_forward_paths(start_dataframe_name, end_dataframe_name)
next(paths)
second_path = next(paths, None)
return not second_path
###########################################################################
# DataFrame creation methods ##############################################
###########################################################################
def add_dataframe(
self,
dataframe,
dataframe_name=None,
index=None,
logical_types=None,
semantic_tags=None,
make_index=False,
time_index=None,
secondary_time_index=None,
already_sorted=False,
):
"""
Add a DataFrame to the EntitySet with Woodwork typing information.
Args:
dataframe (pandas.DataFrame) : Dataframe containing the data.
dataframe_name (str, optional) : Unique name to associate with this dataframe. Must be
provided if Woodwork is not initialized on the input DataFrame.
index (str, optional): Name of the column used to index the dataframe.
Must be unique. If None, take the first column.
logical_types (dict[str -> Woodwork.LogicalTypes/str, optional]):
Keys are column names and values are logical types. Will be inferred if not specified.
semantic_tags (dict[str -> str/set], optional):
Keys are column names and values are semantic tags.
make_index (bool, optional) : If True, assume index does not
exist as a column in dataframe, and create a new column of that name
using integers. Otherwise, assume index exists.
time_index (str, optional): Name of the column containing
time data. Type must be numeric or datetime in nature.
secondary_time_index (dict[str -> list[str]]): Name of column containing time data to
be used as a secondary time index mapped to a list of the columns in the dataframe
associated with that secondary time index.
already_sorted (bool, optional) : If True, assumes that input dataframe
is already sorted by time. Defaults to False.
Notes:
Will infer logical types from the data.
Example:
.. ipython:: python
import featuretools as ft
import pandas as pd
transactions_df = pd.DataFrame({"id": [1, 2, 3, 4, 5, 6],
"session_id": [1, 2, 1, 3, 4, 5],
"amount": [100.40, 20.63, 33.32, 13.12, 67.22, 1.00],
"transaction_time": pd.date_range(start="10:00", periods=6, freq="10s"),
"fraud": [True, False, True, False, True, True]})
es = ft.EntitySet("example")
es.add_dataframe(dataframe_name="transactions",
index="id",
time_index="transaction_time",
dataframe=transactions_df)
es["transactions"]
"""
logical_types = logical_types or {}
semantic_tags = semantic_tags or {}
if len(self.dataframes) > 0:
if not isinstance(dataframe, type(self.dataframes[0])):
raise ValueError(
"All dataframes must be of the same type. "
"Cannot add dataframe of type {} to an entityset with existing dataframes "
"of type {}".format(type(dataframe), type(self.dataframes[0])),
)
# Only allow string column names
non_string_names = [
name for name in dataframe.columns if not isinstance(name, str)
]
if non_string_names:
raise ValueError(
"All column names must be strings (Columns {} "
"are not strings)".format(non_string_names),
)
if dataframe.ww.schema is None:
if dataframe_name is None:
raise ValueError(
"Cannot add dataframe to EntitySet without a name. "
"Please provide a value for the dataframe_name parameter.",
)
# Warn when performing inference on Dask or Spark DataFrames
if not set(dataframe.columns).issubset(set(logical_types.keys())) and (
is_instance(dataframe, dd, "DataFrame")
or is_instance(dataframe, ps, "DataFrame")
):
warnings.warn(
"Performing type inference on Dask or Spark DataFrames may be computationally intensive. "
"Specify logical types for each column to speed up EntitySet initialization.",
)
index_was_created, index, dataframe = _get_or_create_index(
index,
make_index,
dataframe,
)
dataframe.ww.init(
name=dataframe_name,
index=index,
time_index=time_index,
logical_types=logical_types,
semantic_tags=semantic_tags,
already_sorted=already_sorted,
)
if index_was_created:
dataframe.ww.metadata["created_index"] = index
else:
if dataframe.ww.name is None:
raise ValueError(
"Cannot add a Woodwork DataFrame to EntitySet without a name",
)
if dataframe.ww.index is None:
raise ValueError(
"Cannot add Woodwork DataFrame to EntitySet without index",
)
extra_params = []
if index is not None:
extra_params.append("index")
if time_index is not None:
extra_params.append("time_index")
if logical_types:
extra_params.append("logical_types")
if make_index:
extra_params.append("make_index")
if semantic_tags:
extra_params.append("semantic_tags")
if already_sorted:
extra_params.append("already_sorted")
if dataframe_name is not None and dataframe_name != dataframe.ww.name:
extra_params.append("dataframe_name")
if extra_params:
warnings.warn(
"A Woodwork-initialized DataFrame was provided, so the following parameters were ignored: "
+ ", ".join(extra_params),
)
if dataframe.ww.time_index is not None:
self._check_uniform_time_index(dataframe)
self._check_secondary_time_index(dataframe)
if secondary_time_index:
self._set_secondary_time_index(
dataframe,
secondary_time_index=secondary_time_index,
)
dataframe = self._normalize_values(dataframe)
self.dataframe_dict[dataframe.ww.name] = dataframe
self.reset_data_description()
self._add_references_to_metadata(dataframe)
return self
def __setitem__(self, key, value):
self.add_dataframe(dataframe=value, dataframe_name=key)
def normalize_dataframe(
self,
base_dataframe_name,
new_dataframe_name,
index,
additional_columns=None,
copy_columns=None,
make_time_index=None,
make_secondary_time_index=None,
new_dataframe_time_index=None,
new_dataframe_secondary_time_index=None,
):
"""Create a new dataframe and relationship from unique values of an existing column.
Args:
base_dataframe_name (str) : Dataframe name from which to split.
new_dataframe_name (str): Name of the new dataframe.
index (str): Column in old dataframe
that will become index of new dataframe. Relationship
will be created across this column.
additional_columns (list[str]):
List of column names to remove from
base_dataframe and move to new dataframe.
copy_columns (list[str]): List of
column names to copy from old dataframe
and move to new dataframe.
make_time_index (bool or str, optional): Create time index for new dataframe based
on time index in base_dataframe, optionally specifying which column in base_dataframe
to use for time_index. If specified as True without a specific column name,
uses the primary time index. Defaults to True if base dataframe has a time index.
make_secondary_time_index (dict[str -> list[str]], optional): Create a secondary time index
from key. Values of dictionary are the columns to associate with a secondary time index.
Only one secondary time index is allowed. If None, only associate the time index.
new_dataframe_time_index (str, optional): Rename new dataframe time index.
new_dataframe_secondary_time_index (str, optional): Rename new dataframe secondary time index.
"""
base_dataframe = self.dataframe_dict[base_dataframe_name]
additional_columns = additional_columns or []
copy_columns = copy_columns or []
for list_name, col_list in {
"copy_columns": copy_columns,
"additional_columns": additional_columns,
}.items():
if not isinstance(col_list, list):
raise TypeError(
"'{}' must be a list, but received type {}".format(
list_name,
type(col_list),
),
)
if len(col_list) != len(set(col_list)):
raise ValueError(
f"'{list_name}' contains duplicate columns. All columns must be unique.",
)
for col_name in col_list:
if col_name == index:
raise ValueError(
"Not adding {} as both index and column in {}".format(
col_name,
list_name,
),
)
for col in additional_columns:
if col == base_dataframe.ww.time_index:
raise ValueError(
"Not moving {} as it is the base time index column. Perhaps, move the column to the copy_columns.".format(
col,
),
)
if isinstance(make_time_index, str):
if make_time_index not in base_dataframe.columns:
raise ValueError(
"'make_time_index' must be a column in the base dataframe",
)
elif make_time_index not in additional_columns + copy_columns:
raise ValueError(
"'make_time_index' must be specified in 'additional_columns' or 'copy_columns'",
)
if index == base_dataframe.ww.index:
raise ValueError(
"'index' must be different from the index column of the base dataframe",
)
transfer_types = {}
# Types will be a tuple of (logical_type, semantic_tags, column_metadata, column_description)
transfer_types[index] = (
base_dataframe.ww.logical_types[index],
base_dataframe.ww.semantic_tags[index],
base_dataframe.ww.columns[index].metadata,
base_dataframe.ww.columns[index].description,
)
for col_name in additional_columns + copy_columns:
# Remove any existing time index tags
transfer_types[col_name] = (
base_dataframe.ww.logical_types[col_name],
(base_dataframe.ww.semantic_tags[col_name] - {"time_index"}),
base_dataframe.ww.columns[col_name].metadata,
base_dataframe.ww.columns[col_name].description,
)
# create and add new dataframe
new_dataframe = self[base_dataframe_name].copy()
if make_time_index is None and base_dataframe.ww.time_index is not None:
make_time_index = True
if isinstance(make_time_index, str):
# Set the new time index to make_time_index.
base_time_index = make_time_index
new_dataframe_time_index = make_time_index
already_sorted = new_dataframe_time_index == base_dataframe.ww.time_index
elif make_time_index:
# Create a new time index based on the base dataframe time index.
base_time_index = base_dataframe.ww.time_index
if new_dataframe_time_index is None:
new_dataframe_time_index = "first_%s_time" % (base_dataframe.ww.name)
already_sorted = True
assert (
base_dataframe.ww.time_index is not None
), "Base dataframe doesn't have time_index defined"
if base_time_index not in [col for col in copy_columns]:
copy_columns.append(base_time_index)
time_index_types = (
base_dataframe.ww.logical_types[base_dataframe.ww.time_index],
base_dataframe.ww.semantic_tags[base_dataframe.ww.time_index],
base_dataframe.ww.columns[base_dataframe.ww.time_index].metadata,
base_dataframe.ww.columns[base_dataframe.ww.time_index].description,
)
else:
# If base_time_index is in copy_columns then we've already added the transfer types
# but since we're changing the name, we have to remove it
time_index_types = transfer_types[base_dataframe.ww.time_index]
del transfer_types[base_dataframe.ww.time_index]
transfer_types[new_dataframe_time_index] = time_index_types
else:
new_dataframe_time_index = None
already_sorted = False
if new_dataframe_time_index is not None and new_dataframe_time_index == index:
raise ValueError(
"time_index and index cannot be the same value, %s"
% (new_dataframe_time_index),
)
selected_columns = (
[index]
+ [col for col in additional_columns]
+ [col for col in copy_columns]
)
new_dataframe = new_dataframe.dropna(subset=[index])
new_dataframe2 = new_dataframe.drop_duplicates(index, keep="first")[
selected_columns
]
if make_time_index:
new_dataframe2 = new_dataframe2.rename(
columns={base_time_index: new_dataframe_time_index},
)
if make_secondary_time_index:
assert (
len(make_secondary_time_index) == 1
), "Can only provide 1 secondary time index"
secondary_time_index = list(make_secondary_time_index.keys())[0]
secondary_columns = [index, secondary_time_index] + list(
make_secondary_time_index.values(),
)[0]
secondary_df = new_dataframe.drop_duplicates(index, keep="last")[
secondary_columns
]
if new_dataframe_secondary_time_index:
secondary_df = secondary_df.rename(
columns={secondary_time_index: new_dataframe_secondary_time_index},
)
secondary_time_index = new_dataframe_secondary_time_index
else:
new_dataframe_secondary_time_index = secondary_time_index
secondary_df = secondary_df.set_index(index)
new_dataframe = new_dataframe2.join(secondary_df, on=index)
else:
new_dataframe = new_dataframe2
base_dataframe_index = index
if make_secondary_time_index:
old_ti_name = list(make_secondary_time_index.keys())[0]
ti_cols = list(make_secondary_time_index.values())[0]
ti_cols = [c if c != old_ti_name else secondary_time_index for c in ti_cols]
make_secondary_time_index = {secondary_time_index: ti_cols}
if is_instance(new_dataframe, ps, "DataFrame"):
already_sorted = False
# will initialize Woodwork on this DataFrame
logical_types = {}
semantic_tags = {}
column_metadata = {}
column_descriptions = {}
for col_name, (ltype, tags, metadata, description) in transfer_types.items():
logical_types[col_name] = ltype
semantic_tags[col_name] = tags - {"time_index"}
column_metadata[col_name] = copy.deepcopy(metadata)