/
dataframe.py
4077 lines (3603 loc) · 163 KB
/
dataframe.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
#!/usr/bin/env python3
#
# Copyright (c) 2012-2023 Snowflake Computing Inc. All rights reserved.
#
import copy
import itertools
import re
import sys
from collections import Counter
from functools import cached_property
from logging import getLogger
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterator,
List,
Optional,
Tuple,
Union,
overload,
)
import snowflake.snowpark
from snowflake.connector.options import installed_pandas
from snowflake.snowpark._internal.analyzer.binary_plan_node import (
AsOf,
Cross,
Except,
Intersect,
Join,
JoinType,
LeftAnti,
LeftSemi,
NaturalJoin,
Union as UnionPlan,
UsingJoin,
create_join_type,
)
from snowflake.snowpark._internal.analyzer.expression import (
Attribute,
Expression,
Literal,
NamedExpression,
Star,
UnresolvedAttribute,
)
from snowflake.snowpark._internal.analyzer.select_statement import (
SET_EXCEPT,
SET_INTERSECT,
SET_UNION,
SET_UNION_ALL,
SelectSnowflakePlan,
SelectStatement,
SelectTableFunction,
)
from snowflake.snowpark._internal.analyzer.snowflake_plan_node import (
CopyIntoTableNode,
Limit,
LogicalPlan,
)
from snowflake.snowpark._internal.analyzer.sort_expression import (
Ascending,
Descending,
SortOrder,
)
from snowflake.snowpark._internal.analyzer.table_function import (
FlattenFunction,
Lateral,
TableFunctionExpression,
TableFunctionJoin,
)
from snowflake.snowpark._internal.analyzer.unary_plan_node import (
CreateDynamicTableCommand,
CreateViewCommand,
Filter,
LocalTempView,
PersistedView,
Project,
Rename,
Sample,
Sort,
Unpivot,
ViewType,
)
from snowflake.snowpark._internal.error_message import SnowparkClientExceptionMessages
from snowflake.snowpark._internal.telemetry import (
add_api_call,
adjust_api_subcalls,
df_api_usage,
df_collect_api_telemetry,
df_to_relational_group_df_api_usage,
)
from snowflake.snowpark._internal.type_utils import (
ColumnOrName,
ColumnOrSqlExpr,
LiteralType,
snow_type_to_dtype_str,
)
from snowflake.snowpark._internal.utils import (
SKIP_LEVELS_THREE,
SKIP_LEVELS_TWO,
TempObjectType,
check_is_pandas_dataframe_in_to_pandas,
column_to_bool,
create_or_update_statement_params_with_query_tag,
deprecated,
escape_quotes,
experimental,
generate_random_alphanumeric,
get_copy_into_table_options,
is_snowflake_quoted_id_case_insensitive,
is_snowflake_unquoted_suffix_case_insensitive,
is_sql_select_statement,
parse_positional_args_to_list,
parse_table_name,
private_preview,
quote_name,
random_name_for_temp_object,
validate_object_name,
)
from snowflake.snowpark.async_job import AsyncJob, _AsyncResultType
from snowflake.snowpark.column import Column, _to_col_if_sql_expr, _to_col_if_str
from snowflake.snowpark.dataframe_analytics_functions import DataFrameAnalyticsFunctions
from snowflake.snowpark.dataframe_na_functions import DataFrameNaFunctions
from snowflake.snowpark.dataframe_stat_functions import DataFrameStatFunctions
from snowflake.snowpark.dataframe_writer import DataFrameWriter
from snowflake.snowpark.exceptions import SnowparkDataframeException
from snowflake.snowpark.functions import (
abs as abs_,
col,
count,
lit,
max as max_,
mean,
min as min_,
random,
row_number,
sql_expr,
stddev,
to_char,
)
from snowflake.snowpark.mock._select_statement import MockSelectStatement
from snowflake.snowpark.row import Row
from snowflake.snowpark.table_function import (
TableFunctionCall,
_create_table_function_expression,
_ExplodeFunctionCall,
_get_cols_after_explode_join,
_get_cols_after_join_table,
)
from snowflake.snowpark.types import StringType, StructType, _NumericType
# Python 3.8 needs to use typing.Iterable because collections.abc.Iterable is not subscriptable
# Python 3.9 can use both
# Python 3.10 needs to use collections.abc.Iterable because typing.Iterable is removed
if sys.version_info <= (3, 9):
from typing import Iterable
else:
from collections.abc import Iterable
if TYPE_CHECKING:
from table import Table # pragma: no cover
_logger = getLogger(__name__)
_ONE_MILLION = 1000000
_NUM_PREFIX_DIGITS = 4
_UNALIASED_REGEX = re.compile(f"""._[a-zA-Z0-9]{{{_NUM_PREFIX_DIGITS}}}_(.*)""")
def _generate_prefix(prefix: str) -> str:
return f"{prefix}_{generate_random_alphanumeric(_NUM_PREFIX_DIGITS)}_"
def _get_unaliased(col_name: str) -> List[str]:
unaliased = []
c = col_name
while match := _UNALIASED_REGEX.match(c):
c = match.group(1)
unaliased.append(c)
return unaliased
def _alias_if_needed(
df: "DataFrame",
c: str,
prefix: Optional[str],
suffix: Optional[str],
common_col_names: List[str],
):
col = df.col(c)
unquoted_col_name = c.strip('"')
if c in common_col_names:
if suffix:
column_case_insensitive = is_snowflake_quoted_id_case_insensitive(c)
suffix_unqouted_case_insensitive = (
is_snowflake_unquoted_suffix_case_insensitive(suffix)
)
return col.alias(
f'"{unquoted_col_name}{suffix.upper()}"'
if column_case_insensitive and suffix_unqouted_case_insensitive
else f'''"{unquoted_col_name}{escape_quotes(suffix.strip('"'))}"'''
)
return col.alias(f'"{prefix}{unquoted_col_name}"')
else:
return col.alias(f'"{unquoted_col_name}"')
def _disambiguate(
lhs: "DataFrame",
rhs: "DataFrame",
join_type: JoinType,
using_columns: Iterable[str],
*,
lsuffix: str = "",
rsuffix: str = "",
) -> Tuple["DataFrame", "DataFrame"]:
if lsuffix == rsuffix and lsuffix:
raise ValueError(
f"'lsuffix' and 'rsuffix' must be different if they're not empty. You set {lsuffix!r} to both."
)
# Normalize the using columns.
normalized_using_columns = {quote_name(c) for c in using_columns}
# Check if the LHS and RHS have columns in common. If they don't just return them as-is. If
# they do have columns in common, alias the common columns with randomly generated l_
# and r_ prefixes for the left and right sides respectively.
# We assume the column names from the schema are normalized and quoted.
lhs_names = [attr.name for attr in lhs._output]
rhs_names = [attr.name for attr in rhs._output]
common_col_names = [
n
for n in lhs_names
if n in set(rhs_names) and n not in normalized_using_columns
]
if common_col_names:
# We use the session of the LHS DataFrame to report this telemetry
lhs._session._conn._telemetry_client.send_alias_in_join_telemetry()
lsuffix = lsuffix or lhs._alias
rsuffix = rsuffix or rhs._alias
suffix_provided = lsuffix or rsuffix
lhs_prefix = _generate_prefix("l") if not suffix_provided else ""
rhs_prefix = _generate_prefix("r") if not suffix_provided else ""
lhs_remapped = lhs.select(
[
_alias_if_needed(
lhs,
name,
lhs_prefix,
lsuffix,
[] if isinstance(join_type, (LeftSemi, LeftAnti)) else common_col_names,
)
for name in lhs_names
]
)
rhs_remapped = rhs.select(
[
_alias_if_needed(rhs, name, rhs_prefix, rsuffix, common_col_names)
for name in rhs_names
]
)
return lhs_remapped, rhs_remapped
class DataFrame:
"""Represents a lazily-evaluated relational dataset that contains a collection
of :class:`Row` objects with columns defined by a schema (column name and type).
A DataFrame is considered lazy because it encapsulates the computation or query
required to produce a relational dataset. The computation is not performed until
you call a method that performs an action (e.g. :func:`collect`).
**Creating a DataFrame**
You can create a DataFrame in a number of different ways, as shown in the examples
below.
Creating tables and data to run the sample code:
>>> session.sql("create or replace temp table prices(product_id varchar, amount number(10, 2))").collect()
[Row(status='Table PRICES successfully created.')]
>>> session.sql("insert into prices values ('id1', 10.0), ('id2', 20.0)").collect()
[Row(number of rows inserted=2)]
>>> # Create a CSV file to demo load
>>> import tempfile
>>> with tempfile.NamedTemporaryFile(mode="w+t") as t:
... t.writelines(["id1, Product A", "\\n" "id2, Product B"])
... t.flush()
... create_stage_result = session.sql("create temp stage test_stage").collect()
... put_result = session.file.put(t.name, "@test_stage/test_dir")
Example 1
Creating a DataFrame by reading a table in Snowflake::
>>> df_prices = session.table("prices")
Example 2
Creating a DataFrame by reading files from a stage::
>>> from snowflake.snowpark.types import StructType, StructField, IntegerType, StringType
>>> df_catalog = session.read.schema(StructType([StructField("id", StringType()), StructField("name", StringType())])).csv("@test_stage/test_dir")
>>> df_catalog.show()
---------------------
|"ID" |"NAME" |
---------------------
|id1 | Product A |
|id2 | Product B |
---------------------
<BLANKLINE>
Example 3
Creating a DataFrame by specifying a sequence or a range::
>>> session.create_dataframe([(1, "one"), (2, "two")], schema=["col_a", "col_b"]).show()
---------------------
|"COL_A" |"COL_B" |
---------------------
|1 |one |
|2 |two |
---------------------
<BLANKLINE>
>>> session.range(1, 10, 2).to_df("col1").show()
----------
|"COL1" |
----------
|1 |
|3 |
|5 |
|7 |
|9 |
----------
<BLANKLINE>
Example 4
Create a new DataFrame by applying transformations to other existing DataFrames::
>>> df_merged_data = df_catalog.join(df_prices, df_catalog["id"] == df_prices["product_id"])
**Performing operations on a DataFrame**
Broadly, the operations on DataFrame can be divided into two types:
- **Transformations** produce a new DataFrame from one or more existing DataFrames. Note that transformations are lazy and don't cause the DataFrame to be evaluated. If the API does not provide a method to express the SQL that you want to use, you can use :func:`functions.sqlExpr` as a workaround.
- **Actions** cause the DataFrame to be evaluated. When you call a method that performs an action, Snowpark sends the SQL query for the DataFrame to the server for evaluation.
**Transforming a DataFrame**
The following examples demonstrate how you can transform a DataFrame.
Example 5
Using the :func:`select()` method to select the columns that should be in the
DataFrame (similar to adding a ``SELECT`` clause)::
>>> # Return a new DataFrame containing the product_id and amount columns of the prices table.
>>> # This is equivalent to: SELECT PRODUCT_ID, AMOUNT FROM PRICES;
>>> df_price_ids_and_amounts = df_prices.select(col("product_id"), col("amount"))
Example 6
Using the :func:`Column.as_` method to rename a column in a DataFrame (similar
to using ``SELECT col AS alias``)::
>>> # Return a new DataFrame containing the product_id column of the prices table as a column named
>>> # item_id. This is equivalent to: SELECT PRODUCT_ID AS ITEM_ID FROM PRICES;
>>> df_price_item_ids = df_prices.select(col("product_id").as_("item_id"))
Example 7
Using the :func:`filter` method to filter data (similar to adding a ``WHERE`` clause)::
>>> # Return a new DataFrame containing the row from the prices table with the ID 1.
>>> # This is equivalent to:
>>> # SELECT * FROM PRICES WHERE PRODUCT_ID = 1;
>>> df_price1 = df_prices.filter((col("product_id") == 1))
Example 8
Using the :func:`sort()` method to specify the sort order of the data (similar to adding an ``ORDER BY`` clause)::
>>> # Return a new DataFrame for the prices table with the rows sorted by product_id.
>>> # This is equivalent to: SELECT * FROM PRICES ORDER BY PRODUCT_ID;
>>> df_sorted_prices = df_prices.sort(col("product_id"))
Example 9
Using :meth:`agg` method to aggregate results.
>>> import snowflake.snowpark.functions as f
>>> df_prices.agg(("amount", "sum")).collect()
[Row(SUM(AMOUNT)=Decimal('30.00'))]
>>> df_prices.agg(f.sum("amount")).collect()
[Row(SUM(AMOUNT)=Decimal('30.00'))]
>>> # rename the aggregation column name
>>> df_prices.agg(f.sum("amount").alias("total_amount"), f.max("amount").alias("max_amount")).collect()
[Row(TOTAL_AMOUNT=Decimal('30.00'), MAX_AMOUNT=Decimal('20.00'))]
Example 10
Using the :func:`group_by()` method to return a
:class:`RelationalGroupedDataFrame` that you can use to group and aggregate
results (similar to adding a ``GROUP BY`` clause).
:class:`RelationalGroupedDataFrame` provides methods for aggregating results, including:
- :func:`RelationalGroupedDataFrame.avg()` (equivalent to AVG(column))
- :func:`RelationalGroupedDataFrame.count()` (equivalent to COUNT())
- :func:`RelationalGroupedDataFrame.max()` (equivalent to MAX(column))
- :func:`RelationalGroupedDataFrame.median()` (equivalent to MEDIAN(column))
- :func:`RelationalGroupedDataFrame.min()` (equivalent to MIN(column))
- :func:`RelationalGroupedDataFrame.sum()` (equivalent to SUM(column))
>>> # Return a new DataFrame for the prices table that computes the sum of the prices by
>>> # category. This is equivalent to:
>>> # SELECT CATEGORY, SUM(AMOUNT) FROM PRICES GROUP BY CATEGORY
>>> df_total_price_per_category = df_prices.group_by(col("product_id")).sum(col("amount"))
>>> # Have multiple aggregation values with the group by
>>> import snowflake.snowpark.functions as f
>>> df_summary = df_prices.group_by(col("product_id")).agg(f.sum(col("amount")).alias("total_amount"), f.avg("amount"))
>>> df_summary.show()
-------------------------------------------------
|"PRODUCT_ID" |"TOTAL_AMOUNT" |"AVG(AMOUNT)" |
-------------------------------------------------
|id1 |10.00 |10.00000000 |
|id2 |20.00 |20.00000000 |
-------------------------------------------------
<BLANKLINE>
Example 11
Using windowing functions. Refer to :class:`Window` for more details.
>>> from snowflake.snowpark import Window
>>> from snowflake.snowpark.functions import row_number
>>> df_prices.with_column("price_rank", row_number().over(Window.order_by(col("amount").desc()))).show()
------------------------------------------
|"PRODUCT_ID" |"AMOUNT" |"PRICE_RANK" |
------------------------------------------
|id2 |20.00 |1 |
|id1 |10.00 |2 |
------------------------------------------
<BLANKLINE>
Example 12
Handling missing values. Refer to :class:`DataFrameNaFunctions` for more details.
>>> df = session.create_dataframe([[1, None, 3], [4, 5, None]], schema=["a", "b", "c"])
>>> df.na.fill({"b": 2, "c": 6}).show()
-------------------
|"A" |"B" |"C" |
-------------------
|1 |2 |3 |
|4 |5 |6 |
-------------------
<BLANKLINE>
**Performing an action on a DataFrame**
The following examples demonstrate how you can perform an action on a DataFrame.
Example 13
Performing a query and returning an array of Rows::
>>> df_prices.collect()
[Row(PRODUCT_ID='id1', AMOUNT=Decimal('10.00')), Row(PRODUCT_ID='id2', AMOUNT=Decimal('20.00'))]
Example 14
Performing a query and print the results::
>>> df_prices.show()
---------------------------
|"PRODUCT_ID" |"AMOUNT" |
---------------------------
|id1 |10.00 |
|id2 |20.00 |
---------------------------
<BLANKLINE>
Example 15
Calculating statistics values. Refer to :class:`DataFrameStatFunctions` for more details.
>>> df = session.create_dataframe([[1, 2], [3, 4], [5, -1]], schema=["a", "b"])
>>> df.stat.corr("a", "b")
-0.5960395606792697
Example 16
Performing a query asynchronously and returning a list of :class:`Row` objects::
>>> df = session.create_dataframe([[float(4), 3, 5], [2.0, -4, 7], [3.0, 5, 6], [4.0, 6, 8]], schema=["a", "b", "c"])
>>> async_job = df.collect_nowait()
>>> async_job.result()
[Row(A=4.0, B=3, C=5), Row(A=2.0, B=-4, C=7), Row(A=3.0, B=5, C=6), Row(A=4.0, B=6, C=8)]
Example 17
Performing a query and transforming it into :class:`pandas.DataFrame` asynchronously::
>>> async_job = df.to_pandas(block=False)
>>> async_job.result()
A B C
0 4.0 3 5
1 2.0 -4 7
2 3.0 5 6
3 4.0 6 8
"""
def __init__(
self,
session: Optional["snowflake.snowpark.Session"] = None,
plan: Optional[LogicalPlan] = None,
is_cached: bool = False,
) -> None:
self._session = session
self._plan = self._session._analyzer.resolve(plan)
if isinstance(plan, (SelectStatement, MockSelectStatement)):
self._select_statement = plan
plan.expr_to_alias.update(self._plan.expr_to_alias)
plan.df_aliased_col_name_to_real_col_name.update(
self._plan.df_aliased_col_name_to_real_col_name
)
else:
self._select_statement = None
self._statement_params = None
self.is_cached: bool = is_cached #: Whether the dataframe is cached.
self._reader: Optional["snowflake.snowpark.DataFrameReader"] = None
self._writer = DataFrameWriter(self)
self._stat = DataFrameStatFunctions(self)
self._analytics = DataFrameAnalyticsFunctions(self)
self.approxQuantile = self.approx_quantile = self._stat.approx_quantile
self.corr = self._stat.corr
self.cov = self._stat.cov
self.crosstab = self._stat.crosstab
self.sampleBy = self.sample_by = self._stat.sample_by
self._na = DataFrameNaFunctions(self)
self.dropna = self._na.drop
self.fillna = self._na.fill
self.replace = self._na.replace
self._alias: Optional[str] = None
@property
def stat(self) -> DataFrameStatFunctions:
return self._stat
@property
def analytics(self) -> DataFrameAnalyticsFunctions:
return self._analytics
@overload
def collect(
self,
*,
statement_params: Optional[Dict[str, str]] = None,
block: bool = True,
log_on_exception: bool = False,
case_sensitive: bool = True,
) -> List[Row]:
... # pragma: no cover
@overload
def collect(
self,
*,
statement_params: Optional[Dict[str, str]] = None,
block: bool = False,
log_on_exception: bool = False,
case_sensitive: bool = True,
) -> AsyncJob:
... # pragma: no cover
@df_collect_api_telemetry
def collect(
self,
*,
statement_params: Optional[Dict[str, str]] = None,
block: bool = True,
log_on_exception: bool = False,
case_sensitive: bool = True,
) -> Union[List[Row], AsyncJob]:
"""Executes the query representing this DataFrame and returns the result as a
list of :class:`Row` objects.
Args:
statement_params: Dictionary of statement level parameters to be set while executing this action.
block: A bool value indicating whether this function will wait until the result is available.
When it is ``False``, this function executes the underlying queries of the dataframe
asynchronously and returns an :class:`AsyncJob`.
case_sensitive: A bool value which controls the case sensitivity of the fields in the
:class:`Row` objects returned by the ``collect``. Defaults to ``True``.
See also:
:meth:`collect_nowait()`
"""
return self._internal_collect_with_tag_no_telemetry(
statement_params=statement_params,
block=block,
log_on_exception=log_on_exception,
case_sensitive=case_sensitive,
)
@df_collect_api_telemetry
def collect_nowait(
self,
*,
statement_params: Optional[Dict[str, str]] = None,
log_on_exception: bool = False,
case_sensitive: bool = True,
) -> AsyncJob:
"""Executes the query representing this DataFrame asynchronously and returns: class:`AsyncJob`.
It is equivalent to ``collect(block=False)``.
Args:
statement_params: Dictionary of statement level parameters to be set while executing this action.
case_sensitive: A bool value which is controls the case sensitivity of the fields in the
:class:`Row` objects after collecting the result using :meth:`AsyncJob.result`. Defaults to
``True``.
See also:
:meth:`collect()`
"""
return self._internal_collect_with_tag_no_telemetry(
statement_params=statement_params,
block=False,
data_type=_AsyncResultType.ROW,
log_on_exception=log_on_exception,
case_sensitive=case_sensitive,
)
def _internal_collect_with_tag_no_telemetry(
self,
*,
statement_params: Optional[Dict[str, str]] = None,
block: bool = True,
data_type: _AsyncResultType = _AsyncResultType.ROW,
log_on_exception: bool = False,
case_sensitive: bool = True,
) -> Union[List[Row], AsyncJob]:
# When executing a DataFrame in any method of snowpark (either public or private),
# we should always call this method instead of collect(), to make sure the
# query tag is set properly.
return self._session._conn.execute(
self._plan,
block=block,
data_type=data_type,
_statement_params=create_or_update_statement_params_with_query_tag(
statement_params or self._statement_params,
self._session.query_tag,
SKIP_LEVELS_THREE,
),
log_on_exception=log_on_exception,
case_sensitive=case_sensitive,
)
_internal_collect_with_tag = df_collect_api_telemetry(
_internal_collect_with_tag_no_telemetry
)
@df_collect_api_telemetry
def _execute_and_get_query_id(
self, *, statement_params: Optional[Dict[str, str]] = None
) -> str:
"""This method is only used in stored procedures."""
return self._session._conn.get_result_query_id(
self._plan,
_statement_params=create_or_update_statement_params_with_query_tag(
statement_params or self._statement_params,
self._session.query_tag,
SKIP_LEVELS_THREE,
),
)
@overload
def to_local_iterator(
self,
*,
statement_params: Optional[Dict[str, str]] = None,
block: bool = True,
case_sensitive: bool = True,
) -> Iterator[Row]:
... # pragma: no cover
@overload
def to_local_iterator(
self,
*,
statement_params: Optional[Dict[str, str]] = None,
block: bool = False,
case_sensitive: bool = True,
) -> AsyncJob:
... # pragma: no cover
@df_collect_api_telemetry
def to_local_iterator(
self,
*,
statement_params: Optional[Dict[str, str]] = None,
block: bool = True,
case_sensitive: bool = True,
) -> Union[Iterator[Row], AsyncJob]:
"""Executes the query representing this DataFrame and returns an iterator
of :class:`Row` objects that you can use to retrieve the results.
Unlike :meth:`collect`, this method does not load all data into memory
at once.
Example::
>>> df = session.table("prices")
>>> for row in df.to_local_iterator():
... print(row)
Row(PRODUCT_ID='id1', AMOUNT=Decimal('10.00'))
Row(PRODUCT_ID='id2', AMOUNT=Decimal('20.00'))
Args:
statement_params: Dictionary of statement level parameters to be set while executing this action.
block: A bool value indicating whether this function will wait until the result is available.
When it is ``False``, this function executes the underlying queries of the dataframe
asynchronously and returns an :class:`AsyncJob`.
case_sensitive: A bool value which controls the case sensitivity of the fields in the
:class:`Row` objects returned by the ``to_local_iterator``. Defaults to ``True``.
"""
return self._session._conn.execute(
self._plan,
to_iter=True,
block=block,
data_type=_AsyncResultType.ITERATOR,
_statement_params=create_or_update_statement_params_with_query_tag(
statement_params or self._statement_params,
self._session.query_tag,
SKIP_LEVELS_THREE,
),
case_sensitive=case_sensitive,
)
def __copy__(self) -> "DataFrame":
if self._select_statement:
new_plan = copy.copy(self._select_statement)
new_plan.column_states = self._select_statement.column_states
new_plan._projection_in_str = self._select_statement.projection_in_str
new_plan._schema_query = self._select_statement.schema_query
new_plan._query_params = self._select_statement.query_params
else:
new_plan = copy.copy(self._plan)
return DataFrame(self._session, new_plan)
if installed_pandas:
import pandas # pragma: no cover
@overload
def to_pandas(
self,
*,
statement_params: Optional[Dict[str, str]] = None,
block: bool = True,
**kwargs: Dict[str, Any],
) -> pandas.DataFrame:
... # pragma: no cover
@overload
def to_pandas(
self,
*,
statement_params: Optional[Dict[str, str]] = None,
block: bool = False,
**kwargs: Dict[str, Any],
) -> AsyncJob:
... # pragma: no cover
@df_collect_api_telemetry
def to_pandas(
self,
*,
statement_params: Optional[Dict[str, str]] = None,
block: bool = True,
**kwargs: Dict[str, Any],
) -> Union["pandas.DataFrame", AsyncJob]:
"""
Executes the query representing this DataFrame and returns the result as a
`pandas DataFrame <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_.
When the data is too large to fit into memory, you can use :meth:`to_pandas_batches`.
Args:
statement_params: Dictionary of statement level parameters to be set while executing this action.
block: A bool value indicating whether this function will wait until the result is available.
When it is ``False``, this function executes the underlying queries of the dataframe
asynchronously and returns an :class:`AsyncJob`.
Note:
1. This method is only available if pandas is installed and available.
2. If you use :func:`Session.sql` with this method, the input query of
:func:`Session.sql` can only be a SELECT statement.
"""
result = self._session._conn.execute(
self._plan,
to_pandas=True,
block=block,
data_type=_AsyncResultType.PANDAS,
_statement_params=create_or_update_statement_params_with_query_tag(
statement_params or self._statement_params,
self._session.query_tag,
SKIP_LEVELS_TWO,
),
**kwargs,
)
# if the returned result is not a pandas dataframe, raise Exception
# this might happen when calling this method with non-select commands
# e.g., session.sql("create ...").to_pandas()
if block:
check_is_pandas_dataframe_in_to_pandas(result)
return result
if installed_pandas:
import pandas
@overload
def to_pandas_batches(
self,
*,
statement_params: Optional[Dict[str, str]] = None,
block: bool = True,
**kwargs: Dict[str, Any],
) -> Iterator[pandas.DataFrame]:
... # pragma: no cover
@overload
def to_pandas_batches(
self,
*,
statement_params: Optional[Dict[str, str]] = None,
block: bool = False,
**kwargs: Dict[str, Any],
) -> AsyncJob:
... # pragma: no cover
@df_collect_api_telemetry
def to_pandas_batches(
self,
*,
statement_params: Optional[Dict[str, str]] = None,
block: bool = True,
**kwargs: Dict[str, Any],
) -> Union[Iterator["pandas.DataFrame"], AsyncJob]:
"""
Executes the query representing this DataFrame and returns an iterator of
pandas dataframes (containing a subset of rows) that you can use to
retrieve the results.
Unlike :meth:`to_pandas`, this method does not load all data into memory
at once.
Example::
>>> df = session.create_dataframe([[1, 2], [3, 4]], schema=["a", "b"])
>>> for pandas_df in df.to_pandas_batches():
... print(pandas_df)
A B
0 1 2
1 3 4
Args:
statement_params: Dictionary of statement level parameters to be set while executing this action.
block: A bool value indicating whether this function will wait until the result is available.
When it is ``False``, this function executes the underlying queries of the dataframe
asynchronously and returns an :class:`AsyncJob`.
Note:
1. This method is only available if pandas is installed and available.
2. If you use :func:`Session.sql` with this method, the input query of
:func:`Session.sql` can only be a SELECT statement.
"""
return self._session._conn.execute(
self._plan,
to_pandas=True,
to_iter=True,
block=block,
data_type=_AsyncResultType.PANDAS_BATCH,
_statement_params=create_or_update_statement_params_with_query_tag(
statement_params or self._statement_params,
self._session.query_tag,
SKIP_LEVELS_TWO,
),
**kwargs,
)
@df_api_usage
def to_df(self, *names: Union[str, Iterable[str]]) -> "DataFrame":
"""
Creates a new DataFrame containing columns with the specified names.
The number of column names that you pass in must match the number of columns in the existing
DataFrame.
Examples::
>>> df1 = session.range(1, 10, 2).to_df("col1")
>>> df2 = session.range(1, 10, 2).to_df(["col1"])
Args:
names: list of new column names
"""
col_names = parse_positional_args_to_list(*names)
if not all(isinstance(n, str) for n in col_names):
raise TypeError(
"Invalid input type in to_df(), expected str or a list of strs."
)
if len(self._output) != len(col_names):
raise ValueError(
f"The number of columns doesn't match. "
f"Old column names ({len(self._output)}): "
f"{','.join(attr.name for attr in self._output)}. "
f"New column names ({len(col_names)}): {','.join(col_names)}."
)
new_cols = []
for attr, name in zip(self._output, col_names):
new_cols.append(Column(attr).alias(name))
return self.select(new_cols)
def __getitem__(self, item: Union[str, Column, List, Tuple, int]):
if isinstance(item, str):
return self.col(item)
elif isinstance(item, Column):
return self.filter(item)
elif isinstance(item, (list, tuple)):
return self.select(item)
elif isinstance(item, int):
return self.__getitem__(self.columns[item])
else:
raise TypeError(f"Unexpected item type: {type(item)}")
def __getattr__(self, name: str):
# Snowflake DB ignores cases when there is no quotes.
if name.lower() not in [c.lower() for c in self.columns]:
raise AttributeError(
f"{self.__class__.__name__} object has no attribute {name}"
)
return self.col(name)
@property
def columns(self) -> List[str]:
"""Returns all column names as a list.
The returned column names are consistent with the Snowflake database object `identifier syntax <https://docs.snowflake.com/en/sql-reference/identifiers-syntax.html>`_.
================================== ==========================
Column name used to create a table Column name returned in str
================================== ==========================
a 'A'
A 'A'
"a" '"a"'
"a b" '"a b"'
"a""b" '"a""b"'
================================== ==========================
"""
return self.schema.names
def col(self, col_name: str) -> Column:
"""Returns a reference to a column in the DataFrame."""
if col_name == "*":
return Column(Star(self._output))
else:
return Column(self._resolve(col_name))
@df_api_usage
def select(
self,
*cols: Union[
Union[ColumnOrName, TableFunctionCall],
Iterable[Union[ColumnOrName, TableFunctionCall]],
],
) -> "DataFrame":
"""Returns a new DataFrame with the specified Column expressions as output
(similar to SELECT in SQL). Only the Columns specified as arguments will be
present in the resulting DataFrame.
You can use any :class:`Column` expression or strings for named columns.
Example 1::
>>> df = session.create_dataframe([[1, "some string value", 3, 4]], schema=["col1", "col2", "col3", "col4"])
>>> df_selected = df.select(col("col1"), col("col2").substr(0, 10), df["col3"] + df["col4"])
Example 2::
>>> df_selected = df.select("col1", "col2", "col3")
Example 3::
>>> df_selected = df.select(["col1", "col2", "col3"])
Example 4::
>>> df_selected = df.select(df["col1"], df.col2, df.col("col3"))
Example 5::