Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

2170

2171

2172

2173

2174

2175

2176

2177

2178

2179

2180

2181

2182

2183

2184

2185

2186

2187

2188

2189

2190

2191

2192

2193

2194

2195

2196

2197

2198

2199

2200

2201

2202

2203

2204

2205

2206

2207

2208

2209

2210

2211

2212

2213

2214

2215

2216

2217

2218

2219

2220

2221

2222

2223

2224

2225

2226

2227

2228

2229

2230

2231

2232

2233

2234

2235

2236

2237

2238

2239

2240

2241

2242

2243

2244

2245

2246

2247

2248

2249

2250

2251

2252

2253

2254

2255

2256

2257

2258

2259

2260

2261

2262

2263

2264

2265

2266

2267

2268

2269

2270

2271

2272

2273

2274

2275

2276

2277

2278

2279

2280

2281

2282

2283

2284

2285

2286

2287

2288

2289

2290

2291

2292

2293

2294

2295

2296

2297

2298

2299

2300

2301

2302

2303

2304

2305

2306

2307

2308

2309

2310

2311

2312

2313

2314

2315

2316

2317

2318

2319

2320

2321

2322

2323

2324

2325

2326

2327

2328

2329

2330

2331

2332

2333

2334

2335

2336

2337

2338

2339

2340

2341

2342

2343

2344

2345

2346

2347

2348

2349

2350

2351

2352

2353

2354

2355

2356

2357

2358

2359

2360

2361

2362

2363

2364

2365

2366

2367

2368

2369

2370

2371

2372

2373

2374

2375

2376

2377

2378

2379

2380

2381

2382

2383

2384

2385

2386

2387

2388

2389

2390

2391

2392

2393

2394

2395

2396

2397

2398

2399

2400

2401

2402

2403

2404

2405

2406

2407

2408

2409

2410

2411

2412

2413

2414

2415

2416

2417

2418

2419

2420

2421

2422

2423

2424

2425

2426

2427

2428

2429

2430

2431

2432

2433

2434

2435

2436

2437

2438

2439

2440

2441

2442

2443

2444

2445

2446

2447

2448

2449

2450

2451

2452

2453

2454

2455

2456

2457

2458

2459

2460

2461

2462

2463

2464

2465

2466

2467

2468

2469

2470

2471

2472

2473

2474

2475

2476

2477

2478

2479

2480

2481

2482

2483

2484

2485

2486

2487

2488

2489

2490

2491

2492

2493

2494

2495

2496

2497

2498

2499

2500

2501

2502

2503

2504

2505

2506

2507

2508

2509

2510

2511

2512

2513

2514

2515

2516

2517

2518

2519

2520

2521

2522

2523

2524

2525

2526

2527

2528

2529

2530

2531

2532

2533

2534

2535

2536

2537

2538

2539

2540

2541

2542

2543

2544

2545

2546

2547

2548

2549

2550

2551

2552

2553

2554

2555

2556

2557

2558

2559

2560

2561

2562

2563

2564

2565

2566

2567

2568

2569

2570

2571

2572

2573

2574

2575

2576

2577

2578

2579

2580

2581

2582

2583

2584

2585

2586

2587

2588

2589

2590

2591

2592

2593

2594

2595

2596

2597

2598

2599

2600

2601

2602

2603

2604

2605

2606

2607

2608

2609

2610

2611

2612

2613

2614

2615

2616

2617

2618

2619

2620

2621

2622

2623

2624

2625

2626

2627

2628

2629

2630

2631

2632

2633

2634

2635

2636

2637

2638

2639

2640

2641

2642

2643

2644

2645

2646

2647

2648

2649

2650

2651

2652

2653

2654

2655

2656

2657

2658

2659

2660

2661

2662

2663

2664

2665

2666

2667

2668

2669

2670

2671

2672

2673

2674

2675

2676

2677

2678

2679

2680

2681

2682

2683

2684

2685

2686

2687

2688

2689

2690

2691

2692

2693

2694

2695

2696

2697

2698

2699

2700

2701

2702

2703

2704

2705

2706

2707

2708

2709

2710

2711

2712

2713

2714

2715

2716

2717

2718

2719

2720

2721

2722

2723

2724

2725

2726

2727

2728

2729

2730

2731

2732

2733

2734

2735

2736

2737

2738

2739

2740

2741

2742

2743

2744

2745

2746

2747

2748

2749

2750

2751

2752

2753

2754

2755

2756

2757

2758

2759

2760

2761

2762

2763

2764

2765

2766

2767

2768

2769

2770

2771

2772

2773

2774

2775

2776

2777

2778

2779

2780

2781

2782

2783

2784

2785

2786

2787

2788

2789

2790

2791

2792

2793

2794

2795

2796

2797

2798

2799

2800

2801

2802

2803

2804

2805

2806

2807

2808

2809

2810

2811

2812

2813

2814

2815

2816

2817

2818

2819

2820

2821

2822

2823

2824

2825

2826

2827

2828

2829

2830

2831

2832

2833

2834

2835

2836

2837

2838

2839

2840

2841

2842

2843

2844

2845

2846

2847

2848

2849

2850

2851

2852

2853

2854

2855

2856

2857

2858

2859

2860

2861

2862

2863

2864

2865

2866

2867

2868

2869

2870

2871

2872

2873

2874

2875

2876

2877

2878

2879

2880

2881

2882

2883

2884

2885

2886

2887

2888

2889

2890

2891

2892

2893

2894

2895

2896

2897

2898

2899

2900

2901

2902

2903

2904

2905

2906

2907

2908

2909

2910

2911

2912

2913

2914

2915

2916

2917

2918

2919

2920

2921

2922

2923

2924

2925

2926

2927

2928

2929

2930

2931

2932

2933

2934

2935

2936

2937

2938

2939

2940

2941

2942

2943

2944

2945

2946

2947

2948

2949

2950

2951

2952

2953

2954

2955

2956

2957

2958

2959

2960

2961

2962

2963

2964

2965

2966

2967

2968

2969

2970

2971

2972

2973

2974

2975

2976

2977

2978

2979

2980

2981

2982

2983

2984

2985

2986

2987

2988

2989

2990

2991

2992

2993

2994

2995

2996

2997

2998

2999

3000

3001

3002

3003

3004

3005

3006

3007

3008

3009

3010

3011

3012

3013

3014

3015

3016

3017

3018

3019

3020

3021

3022

3023

3024

3025

3026

3027

3028

3029

3030

3031

3032

3033

3034

3035

3036

3037

3038

3039

3040

3041

3042

3043

3044

3045

3046

3047

3048

3049

3050

3051

3052

3053

3054

3055

3056

3057

3058

3059

3060

3061

3062

3063

3064

3065

3066

3067

3068

3069

3070

3071

3072

3073

3074

3075

3076

3077

3078

3079

3080

3081

3082

3083

3084

3085

3086

3087

3088

3089

3090

3091

3092

3093

3094

3095

3096

3097

3098

3099

3100

3101

3102

3103

3104

3105

3106

3107

3108

3109

3110

3111

3112

3113

3114

3115

3116

3117

3118

3119

3120

3121

3122

3123

3124

3125

3126

3127

3128

3129

3130

3131

3132

3133

3134

3135

3136

3137

3138

3139

3140

3141

3142

3143

3144

3145

3146

3147

3148

3149

3150

3151

3152

3153

3154

3155

3156

3157

3158

3159

3160

3161

3162

3163

3164

3165

3166

3167

3168

3169

3170

3171

3172

3173

3174

3175

3176

3177

3178

3179

3180

3181

3182

3183

3184

3185

3186

3187

3188

3189

3190

3191

3192

3193

3194

3195

3196

3197

3198

3199

3200

3201

3202

3203

3204

3205

3206

3207

3208

3209

3210

3211

3212

3213

3214

3215

3216

3217

3218

3219

3220

3221

3222

3223

3224

3225

3226

3227

3228

3229

3230

3231

3232

3233

3234

3235

3236

3237

3238

3239

3240

3241

3242

3243

3244

3245

3246

3247

3248

3249

3250

3251

3252

3253

3254

3255

3256

3257

3258

3259

3260

3261

3262

3263

3264

3265

3266

3267

3268

3269

3270

3271

3272

3273

3274

3275

3276

3277

3278

3279

3280

3281

3282

3283

3284

3285

3286

3287

3288

3289

3290

3291

3292

3293

3294

3295

3296

3297

3298

3299

3300

3301

3302

3303

3304

3305

3306

3307

3308

3309

3310

3311

3312

3313

3314

3315

3316

3317

3318

3319

3320

3321

3322

3323

3324

3325

3326

3327

3328

3329

3330

3331

3332

3333

3334

3335

3336

3337

3338

3339

3340

3341

3342

3343

3344

3345

3346

3347

3348

3349

3350

3351

3352

3353

3354

3355

3356

3357

3358

3359

3360

3361

3362

3363

3364

3365

3366

3367

3368

3369

3370

3371

3372

3373

3374

3375

3376

3377

3378

3379

3380

3381

3382

3383

3384

3385

3386

3387

3388

3389

3390

3391

3392

3393

3394

3395

3396

3397

3398

3399

3400

3401

3402

3403

3404

3405

3406

3407

3408

3409

3410

3411

3412

3413

3414

3415

3416

3417

3418

3419

3420

3421

3422

3423

3424

3425

3426

3427

3428

3429

3430

3431

3432

3433

3434

3435

3436

3437

3438

3439

3440

3441

3442

3443

3444

3445

3446

3447

3448

3449

3450

3451

3452

3453

3454

3455

3456

3457

3458

3459

3460

3461

3462

3463

3464

3465

3466

3467

3468

3469

3470

3471

3472

3473

3474

3475

3476

3477

3478

3479

3480

3481

3482

3483

3484

3485

3486

3487

3488

3489

3490

3491

3492

3493

3494

3495

3496

3497

3498

3499

3500

3501

3502

3503

3504

3505

3506

3507

3508

3509

3510

3511

3512

3513

3514

3515

3516

3517

3518

3519

3520

3521

3522

3523

3524

3525

3526

3527

3528

3529

3530

3531

3532

3533

3534

3535

3536

3537

3538

3539

3540

3541

3542

3543

3544

3545

3546

3547

3548

3549

3550

3551

3552

3553

3554

3555

3556

3557

3558

3559

3560

3561

3562

3563

3564

3565

3566

3567

3568

3569

3570

3571

3572

3573

3574

3575

3576

3577

3578

3579

3580

3581

3582

3583

3584

3585

3586

3587

3588

3589

3590

3591

3592

3593

3594

3595

3596

3597

3598

3599

3600

3601

3602

3603

3604

3605

3606

3607

3608

3609

3610

3611

3612

3613

3614

3615

3616

3617

3618

3619

3620

3621

3622

3623

3624

3625

3626

3627

3628

3629

3630

3631

3632

3633

3634

3635

3636

3637

3638

3639

3640

3641

3642

3643

3644

3645

3646

3647

3648

3649

3650

3651

3652

3653

3654

3655

3656

3657

3658

3659

3660

3661

3662

3663

3664

3665

3666

3667

3668

3669

3670

3671

3672

3673

3674

3675

3676

3677

3678

3679

3680

3681

3682

3683

3684

3685

3686

3687

3688

3689

3690

3691

3692

3693

3694

3695

3696

3697

3698

3699

3700

3701

3702

3703

3704

3705

3706

3707

3708

3709

3710

3711

3712

3713

3714

3715

3716

3717

3718

3719

3720

3721

3722

3723

3724

3725

3726

3727

3728

3729

3730

3731

3732

3733

3734

3735

3736

3737

3738

3739

3740

3741

3742

3743

3744

3745

3746

3747

3748

3749

3750

3751

3752

3753

3754

3755

3756

3757

3758

3759

3760

3761

3762

3763

3764

3765

3766

3767

3768

3769

3770

3771

3772

3773

3774

3775

3776

3777

3778

3779

3780

3781

3782

3783

3784

3785

3786

3787

3788

3789

3790

3791

3792

3793

3794

3795

3796

3797

3798

3799

3800

3801

3802

3803

3804

3805

3806

3807

3808

3809

3810

3811

3812

3813

3814

3815

3816

3817

3818

3819

3820

3821

3822

3823

3824

3825

3826

3827

3828

3829

3830

3831

3832

3833

3834

3835

3836

3837

3838

3839

3840

3841

3842

3843

3844

3845

3846

3847

3848

3849

3850

3851

3852

3853

3854

3855

3856

3857

3858

3859

3860

3861

3862

3863

3864

3865

3866

3867

3868

3869

3870

3871

3872

3873

3874

3875

3876

3877

3878

3879

3880

3881

3882

3883

3884

3885

3886

3887

3888

3889

3890

3891

3892

3893

3894

3895

3896

3897

3898

3899

3900

3901

3902

3903

3904

3905

3906

3907

3908

3909

3910

3911

3912

3913

3914

3915

3916

3917

3918

3919

3920

3921

3922

3923

3924

3925

3926

3927

3928

3929

3930

3931

3932

3933

3934

3935

3936

3937

3938

3939

3940

3941

3942

3943

3944

3945

3946

3947

3948

3949

3950

3951

3952

3953

3954

3955

3956

3957

3958

3959

3960

3961

3962

3963

3964

3965

3966

3967

3968

3969

3970

3971

3972

3973

3974

3975

3976

3977

3978

3979

3980

3981

3982

3983

3984

3985

3986

3987

3988

3989

3990

3991

3992

3993

3994

3995

3996

3997

3998

3999

4000

4001

4002

4003

4004

4005

4006

4007

4008

4009

4010

4011

4012

4013

4014

4015

4016

4017

4018

4019

4020

4021

4022

4023

4024

4025

4026

4027

4028

4029

4030

4031

4032

4033

4034

4035

4036

4037

4038

4039

4040

4041

4042

4043

4044

4045

4046

4047

4048

4049

4050

4051

4052

4053

4054

4055

4056

4057

4058

4059

4060

4061

4062

4063

4064

4065

4066

4067

4068

4069

4070

4071

4072

4073

4074

4075

4076

4077

4078

4079

4080

4081

4082

4083

4084

4085

4086

4087

4088

4089

4090

4091

4092

4093

4094

4095

4096

4097

4098

4099

4100

4101

4102

4103

4104

4105

4106

4107

4108

4109

4110

4111

4112

4113

4114

4115

4116

4117

4118

4119

4120

4121

4122

4123

4124

4125

4126

4127

4128

4129

4130

4131

4132

4133

4134

4135

4136

4137

4138

4139

4140

4141

4142

4143

4144

4145

4146

4147

4148

4149

4150

4151

4152

4153

4154

4155

4156

4157

4158

4159

4160

4161

4162

4163

4164

4165

4166

4167

4168

4169

4170

4171

4172

4173

4174

4175

4176

4177

4178

4179

4180

4181

4182

4183

4184

4185

4186

4187

4188

4189

4190

4191

4192

4193

4194

4195

4196

4197

4198

4199

4200

4201

4202

4203

4204

4205

4206

4207

4208

4209

4210

4211

4212

4213

4214

4215

4216

4217

4218

4219

4220

4221

4222

4223

4224

4225

4226

4227

4228

4229

4230

4231

4232

4233

4234

4235

4236

4237

4238

4239

4240

4241

4242

4243

4244

4245

4246

4247

4248

4249

4250

4251

4252

4253

4254

4255

4256

4257

4258

4259

4260

4261

4262

4263

4264

4265

4266

4267

4268

4269

4270

4271

4272

4273

4274

4275

4276

4277

4278

4279

4280

4281

4282

4283

4284

4285

4286

4287

4288

4289

4290

4291

4292

4293

4294

4295

4296

4297

4298

4299

4300

4301

4302

4303

4304

4305

4306

4307

4308

4309

4310

4311

4312

4313

4314

4315

4316

4317

4318

4319

4320

4321

4322

4323

4324

4325

4326

4327

4328

4329

4330

4331

4332

4333

4334

4335

4336

4337

4338

4339

4340

4341

4342

4343

4344

4345

4346

4347

4348

4349

4350

4351

4352

4353

4354

4355

4356

4357

4358

4359

4360

4361

4362

4363

4364

4365

4366

4367

4368

4369

4370

4371

4372

4373

4374

4375

4376

4377

4378

4379

4380

4381

4382

4383

4384

4385

4386

4387

4388

4389

4390

4391

4392

4393

4394

4395

4396

4397

4398

4399

4400

4401

4402

4403

4404

4405

4406

4407

4408

4409

4410

4411

4412

4413

4414

4415

4416

4417

4418

4419

4420

4421

4422

4423

4424

4425

4426

4427

4428

4429

4430

4431

4432

4433

4434

4435

4436

4437

4438

4439

4440

4441

4442

4443

4444

4445

4446

4447

4448

4449

4450

4451

4452

4453

4454

4455

4456

4457

4458

4459

4460

4461

4462

4463

4464

4465

4466

4467

4468

4469

4470

4471

4472

4473

4474

4475

4476

4477

4478

4479

4480

4481

4482

4483

4484

4485

4486

4487

4488

4489

4490

4491

4492

4493

4494

4495

4496

4497

4498

4499

4500

4501

4502

4503

4504

4505

4506

4507

4508

4509

4510

4511

4512

4513

4514

4515

4516

4517

4518

4519

4520

4521

4522

4523

4524

4525

4526

4527

4528

4529

4530

4531

4532

4533

4534

4535

4536

4537

4538

4539

4540

4541

4542

4543

4544

4545

4546

4547

4548

4549

4550

4551

4552

4553

4554

4555

4556

4557

4558

4559

4560

4561

4562

4563

4564

4565

4566

4567

4568

4569

4570

4571

4572

4573

4574

4575

4576

4577

4578

4579

4580

4581

4582

4583

4584

4585

4586

4587

4588

4589

4590

4591

4592

4593

4594

4595

4596

4597

4598

4599

4600

4601

4602

4603

4604

4605

4606

4607

4608

4609

4610

4611

4612

4613

4614

4615

4616

4617

4618

4619

4620

4621

4622

4623

4624

4625

4626

4627

4628

4629

4630

4631

4632

4633

4634

4635

4636

4637

4638

4639

4640

4641

4642

4643

4644

4645

4646

4647

4648

4649

4650

4651

4652

4653

4654

4655

4656

4657

4658

4659

4660

4661

4662

4663

4664

4665

4666

4667

4668

4669

4670

4671

4672

4673

4674

4675

4676

4677

4678

4679

4680

4681

4682

4683

4684

4685

4686

4687

4688

4689

4690

4691

4692

4693

4694

4695

4696

4697

4698

4699

4700

4701

4702

4703

4704

4705

4706

4707

4708

4709

4710

4711

4712

4713

4714

4715

4716

4717

4718

4719

4720

4721

4722

4723

4724

4725

4726

4727

4728

4729

4730

4731

4732

4733

4734

4735

4736

4737

4738

4739

4740

4741

4742

4743

4744

4745

4746

4747

4748

4749

4750

4751

4752

4753

4754

4755

4756

4757

4758

4759

4760

4761

4762

4763

4764

4765

4766

4767

4768

4769

4770

4771

4772

4773

4774

4775

4776

4777

4778

4779

4780

4781

4782

4783

4784

4785

4786

4787

4788

4789

4790

4791

4792

4793

4794

4795

4796

4797

4798

4799

4800

4801

4802

4803

4804

4805

4806

4807

4808

4809

4810

4811

4812

4813

4814

4815

4816

4817

4818

4819

4820

4821

4822

4823

4824

4825

4826

4827

4828

4829

4830

4831

4832

4833

4834

4835

4836

4837

4838

4839

4840

4841

4842

4843

4844

4845

4846

4847

4848

4849

4850

4851

4852

4853

4854

4855

4856

4857

4858

4859

4860

4861

4862

4863

4864

4865

4866

4867

4868

4869

4870

4871

4872

4873

4874

4875

4876

4877

4878

4879

4880

4881

4882

4883

4884

4885

4886

4887

4888

4889

4890

4891

4892

4893

4894

4895

4896

4897

4898

4899

4900

4901

4902

4903

4904

4905

4906

4907

4908

4909

4910

4911

4912

4913

4914

4915

4916

4917

4918

4919

4920

4921

4922

4923

4924

4925

4926

4927

4928

4929

4930

4931

4932

4933

4934

4935

4936

4937

4938

4939

4940

4941

4942

4943

4944

4945

4946

4947

4948

4949

4950

4951

4952

4953

4954

4955

4956

4957

4958

4959

4960

4961

4962

4963

4964

4965

4966

4967

4968

4969

4970

4971

4972

4973

4974

4975

4976

4977

4978

4979

4980

4981

4982

4983

4984

4985

4986

4987

4988

4989

4990

4991

4992

4993

4994

4995

4996

4997

4998

4999

5000

5001

5002

5003

5004

5005

5006

5007

5008

5009

5010

5011

5012

5013

5014

5015

5016

5017

5018

5019

5020

5021

5022

5023

5024

5025

5026

5027

5028

5029

5030

5031

5032

5033

5034

5035

5036

5037

5038

5039

5040

5041

5042

5043

5044

5045

5046

5047

5048

5049

5050

5051

5052

5053

5054

5055

5056

5057

5058

5059

5060

5061

5062

5063

5064

5065

5066

5067

5068

5069

5070

5071

5072

5073

5074

5075

5076

5077

5078

5079

5080

5081

5082

5083

5084

5085

5086

5087

5088

5089

5090

5091

5092

# 

# Licensed to the Apache Software Foundation (ASF) under one or more 

# contributor license agreements. See the NOTICE file distributed with 

# this work for additional information regarding copyright ownership. 

# The ASF licenses this file to You under the Apache License, Version 2.0 

# (the "License"); you may not use this file except in compliance with 

# the License. You may obtain a copy of the License at 

# 

# http://www.apache.org/licenses/LICENSE-2.0 

# 

# Unless required by applicable law or agreed to in writing, software 

# distributed under the License is distributed on an "AS IS" BASIS, 

# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

# See the License for the specific language governing permissions and 

# limitations under the License. 

# 

 

""" 

A collections of builtin functions 

""" 

import sys 

import functools 

import warnings 

 

from pyspark import since, SparkContext 

from pyspark.rdd import PythonEvalType 

from pyspark.sql.column import Column, _to_java_column, _to_seq, _create_column_from_literal 

from pyspark.sql.dataframe import DataFrame 

from pyspark.sql.types import StringType, DataType 

# Keep UserDefinedFunction import for backwards compatible import; moved in SPARK-22409 

from pyspark.sql.udf import UserDefinedFunction, _create_udf # noqa: F401 

from pyspark.sql.udf import _create_udf 

# Keep pandas_udf and PandasUDFType import for backwards compatible import; moved in SPARK-28264 

from pyspark.sql.pandas.functions import pandas_udf, PandasUDFType # noqa: F401 

from pyspark.sql.utils import to_str 

 

# Note to developers: all of PySpark functions here take string as column names whenever possible. 

# Namely, if columns are referred as arguments, they can be always both Column or string, 

# even though there might be few exceptions for legacy or inevitable reasons. 

# If you are fixing other language APIs together, also please note that Scala side is not the case 

# since it requires to make every single overridden definition. 

 

 

def _get_get_jvm_function(name, sc): 

""" 

Retrieves JVM function identified by name from 

Java gateway associated with sc. 

""" 

return getattr(sc._jvm.functions, name) 

 

 

def _invoke_function(name, *args): 

""" 

Invokes JVM function identified by name with args 

and wraps the result with :class:`~pyspark.sql.Column`. 

""" 

jf = _get_get_jvm_function(name, SparkContext._active_spark_context) 

return Column(jf(*args)) 

 

 

def _invoke_function_over_column(name, col): 

""" 

Invokes unary JVM function identified by name 

and wraps the result with :class:`~pyspark.sql.Column`. 

""" 

return _invoke_function(name, _to_java_column(col)) 

 

 

def _invoke_binary_math_function(name, col1, col2): 

""" 

Invokes binary JVM math function identified by name 

and wraps the result with :class:`~pyspark.sql.Column`. 

""" 

return _invoke_function( 

name, 

# For legacy reasons, the arguments here can be implicitly converted into floats, 

# if they are not columns or strings. 

_to_java_column(col1) if isinstance(col1, (str, Column)) else float(col1), 

_to_java_column(col2) if isinstance(col2, (str, Column)) else float(col2) 

) 

 

 

def _options_to_str(options=None): 

if options: 

return {key: to_str(value) for (key, value) in options.items()} 

return {} 

 

 

def lit(col): 

""" 

Creates a :class:`~pyspark.sql.Column` of literal value. 

 

.. versionadded:: 1.3.0 

 

Examples 

-------- 

>>> df.select(lit(5).alias('height')).withColumn('spark_user', lit(True)).take(1) 

[Row(height=5, spark_user=True)] 

""" 

return col if isinstance(col, Column) else _invoke_function("lit", col) 

 

 

@since(1.3) 

def col(col): 

""" 

Returns a :class:`~pyspark.sql.Column` based on the given column name.' 

Examples 

-------- 

>>> col('x') 

Column<'x'> 

>>> column('x') 

Column<'x'> 

""" 

return _invoke_function("col", col) 

 

 

column = col 

 

 

@since(1.3) 

def asc(col): 

""" 

Returns a sort expression based on the ascending order of the given column name. 

""" 

return ( 

col.asc() if isinstance(col, Column) 

else _invoke_function("asc", col) 

) 

 

 

@since(1.3) 

def desc(col): 

""" 

Returns a sort expression based on the descending order of the given column name. 

""" 

return ( 

col.desc() if isinstance(col, Column) 

else _invoke_function("desc", col) 

) 

 

 

@since(1.3) 

def sqrt(col): 

""" 

Computes the square root of the specified float value. 

""" 

return _invoke_function_over_column("sqrt", col) 

 

 

@since(1.3) 

def abs(col): 

""" 

Computes the absolute value. 

""" 

return _invoke_function_over_column("abs", col) 

 

 

@since(1.3) 

def max(col): 

""" 

Aggregate function: returns the maximum value of the expression in a group. 

""" 

return _invoke_function_over_column("max", col) 

 

 

@since(1.3) 

def min(col): 

""" 

Aggregate function: returns the minimum value of the expression in a group. 

""" 

return _invoke_function_over_column("min", col) 

 

 

@since(1.3) 

def count(col): 

""" 

Aggregate function: returns the number of items in a group. 

""" 

return _invoke_function_over_column("count", col) 

 

 

@since(1.3) 

def sum(col): 

""" 

Aggregate function: returns the sum of all values in the expression. 

""" 

return _invoke_function_over_column("sum", col) 

 

 

@since(1.3) 

def avg(col): 

""" 

Aggregate function: returns the average of the values in a group. 

""" 

return _invoke_function_over_column("avg", col) 

 

 

@since(1.3) 

def mean(col): 

""" 

Aggregate function: returns the average of the values in a group. 

""" 

return _invoke_function_over_column("mean", col) 

 

 

@since(1.3) 

def sumDistinct(col): 

""" 

Aggregate function: returns the sum of distinct values in the expression. 

 

.. deprecated:: 3.2.0 

Use :func:`sum_distinct` instead. 

""" 

warnings.warn("Deprecated in 3.2, use sum_distinct instead.", FutureWarning) 

return sum_distinct(col) 

 

 

@since(3.2) 

def sum_distinct(col): 

""" 

Aggregate function: returns the sum of distinct values in the expression. 

""" 

return _invoke_function_over_column("sum_distinct", col) 

 

 

def product(col): 

""" 

Aggregate function: returns the product of the values in a group. 

 

.. versionadded:: 3.2.0 

 

Parameters 

---------- 

col : str, :class:`Column` 

column containing values to be multiplied together 

 

Examples 

-------- 

>>> df = spark.range(1, 10).toDF('x').withColumn('mod3', col('x') % 3) 

>>> prods = df.groupBy('mod3').agg(product('x').alias('product')) 

>>> prods.orderBy('mod3').show() 

+----+-------+ 

|mod3|product| 

+----+-------+ 

| 0| 162.0| 

| 1| 28.0| 

| 2| 80.0| 

+----+-------+ 

 

""" 

return _invoke_function_over_column("product", col) 

 

 

def acos(col): 

""" 

.. versionadded:: 1.4.0 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

inverse cosine of `col`, as if computed by `java.lang.Math.acos()` 

""" 

return _invoke_function_over_column("acos", col) 

 

 

def acosh(col): 

""" 

Computes inverse hyperbolic cosine of the input column. 

 

.. versionadded:: 3.1.0 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

""" 

return _invoke_function_over_column("acosh", col) 

 

 

def asin(col): 

""" 

.. versionadded:: 1.3.0 

 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

inverse sine of `col`, as if computed by `java.lang.Math.asin()` 

""" 

return _invoke_function_over_column("asin", col) 

 

 

def asinh(col): 

""" 

Computes inverse hyperbolic sine of the input column. 

 

.. versionadded:: 3.1.0 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

""" 

return _invoke_function_over_column("asinh", col) 

 

 

def atan(col): 

""" 

.. versionadded:: 1.4.0 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

inverse tangent of `col`, as if computed by `java.lang.Math.atan()` 

""" 

return _invoke_function_over_column("atan", col) 

 

 

def atanh(col): 

""" 

Computes inverse hyperbolic tangent of the input column. 

 

.. versionadded:: 3.1.0 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

""" 

return _invoke_function_over_column("atanh", col) 

 

 

@since(1.4) 

def cbrt(col): 

""" 

Computes the cube-root of the given value. 

""" 

return _invoke_function_over_column("cbrt", col) 

 

 

@since(1.4) 

def ceil(col): 

""" 

Computes the ceiling of the given value. 

""" 

return _invoke_function_over_column("ceil", col) 

 

 

def cos(col): 

""" 

.. versionadded:: 1.4.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

angle in radians 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

cosine of the angle, as if computed by `java.lang.Math.cos()`. 

""" 

return _invoke_function_over_column("cos", col) 

 

 

def cosh(col): 

""" 

.. versionadded:: 1.4.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

hyperbolic angle 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

hyperbolic cosine of the angle, as if computed by `java.lang.Math.cosh()` 

""" 

return _invoke_function_over_column("cosh", col) 

 

 

@since(1.4) 

def exp(col): 

""" 

Computes the exponential of the given value. 

""" 

return _invoke_function_over_column("exp", col) 

 

 

@since(1.4) 

def expm1(col): 

""" 

Computes the exponential of the given value minus one. 

""" 

return _invoke_function_over_column("expm1", col) 

 

 

@since(1.4) 

def floor(col): 

""" 

Computes the floor of the given value. 

""" 

return _invoke_function_over_column("floor", col) 

 

 

@since(1.4) 

def log(col): 

""" 

Computes the natural logarithm of the given value. 

""" 

return _invoke_function_over_column("log", col) 

 

 

@since(1.4) 

def log10(col): 

""" 

Computes the logarithm of the given value in Base 10. 

""" 

return _invoke_function_over_column("log10", col) 

 

 

@since(1.4) 

def log1p(col): 

""" 

Computes the natural logarithm of the given value plus one. 

""" 

return _invoke_function_over_column("log1p", col) 

 

 

@since(1.4) 

def rint(col): 

""" 

Returns the double value that is closest in value to the argument and 

is equal to a mathematical integer. 

""" 

return _invoke_function_over_column("rint", col) 

 

 

@since(1.4) 

def signum(col): 

""" 

Computes the signum of the given value. 

""" 

return _invoke_function_over_column("signum", col) 

 

 

def sin(col): 

""" 

.. versionadded:: 1.4.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

sine of the angle, as if computed by `java.lang.Math.sin()` 

""" 

return _invoke_function_over_column("sin", col) 

 

 

def sinh(col): 

""" 

.. versionadded:: 1.4.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

hyperbolic angle 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

hyperbolic sine of the given value, 

as if computed by `java.lang.Math.sinh()` 

""" 

return _invoke_function_over_column("sinh", col) 

 

 

def tan(col): 

""" 

.. versionadded:: 1.4.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

angle in radians 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

tangent of the given value, as if computed by `java.lang.Math.tan()` 

""" 

return _invoke_function_over_column("tan", col) 

 

 

def tanh(col): 

""" 

.. versionadded:: 1.4.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

hyperbolic angle 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

hyperbolic tangent of the given value 

as if computed by `java.lang.Math.tanh()` 

""" 

return _invoke_function_over_column("tanh", col) 

 

 

@since(1.4) 

def toDegrees(col): 

""" 

.. deprecated:: 2.1.0 

Use :func:`degrees` instead. 

""" 

warnings.warn("Deprecated in 2.1, use degrees instead.", FutureWarning) 

return degrees(col) 

 

 

@since(1.4) 

def toRadians(col): 

""" 

.. deprecated:: 2.1.0 

Use :func:`radians` instead. 

""" 

warnings.warn("Deprecated in 2.1, use radians instead.", FutureWarning) 

return radians(col) 

 

 

@since(1.4) 

def bitwiseNOT(col): 

""" 

Computes bitwise not. 

 

.. deprecated:: 3.2.0 

Use :func:`bitwise_not` instead. 

""" 

warnings.warn("Deprecated in 3.2, use bitwise_not instead.", FutureWarning) 

return bitwise_not(col) 

 

 

@since(3.2) 

def bitwise_not(col): 

""" 

Computes bitwise not. 

""" 

return _invoke_function_over_column("bitwise_not", col) 

 

 

@since(2.4) 

def asc_nulls_first(col): 

""" 

Returns a sort expression based on the ascending order of the given 

column name, and null values return before non-null values. 

""" 

return ( 

col.asc_nulls_first() if isinstance(col, Column) 

else _invoke_function("asc_nulls_first", col) 

) 

 

 

@since(2.4) 

def asc_nulls_last(col): 

""" 

Returns a sort expression based on the ascending order of the given 

column name, and null values appear after non-null values. 

""" 

return ( 

col.asc_nulls_last() if isinstance(col, Column) 

else _invoke_function("asc_nulls_last", col) 

) 

 

 

@since(2.4) 

def desc_nulls_first(col): 

""" 

Returns a sort expression based on the descending order of the given 

column name, and null values appear before non-null values. 

""" 

return ( 

col.desc_nulls_first() if isinstance(col, Column) 

else _invoke_function("desc_nulls_first", col) 

) 

 

 

@since(2.4) 

def desc_nulls_last(col): 

""" 

Returns a sort expression based on the descending order of the given 

column name, and null values appear after non-null values. 

""" 

return ( 

col.desc_nulls_last() if isinstance(col, Column) 

else _invoke_function("desc_nulls_last", col) 

) 

 

 

@since(1.6) 

def stddev(col): 

""" 

Aggregate function: alias for stddev_samp. 

""" 

return _invoke_function_over_column("stddev", col) 

 

 

@since(1.6) 

def stddev_samp(col): 

""" 

Aggregate function: returns the unbiased sample standard deviation of 

the expression in a group. 

""" 

return _invoke_function_over_column("stddev_samp", col) 

 

 

@since(1.6) 

def stddev_pop(col): 

""" 

Aggregate function: returns population standard deviation of 

the expression in a group. 

""" 

return _invoke_function_over_column("stddev_pop", col) 

 

 

@since(1.6) 

def variance(col): 

""" 

Aggregate function: alias for var_samp 

""" 

return _invoke_function_over_column("variance", col) 

 

 

@since(1.6) 

def var_samp(col): 

""" 

Aggregate function: returns the unbiased sample variance of 

the values in a group. 

""" 

return _invoke_function_over_column("var_samp", col) 

 

 

@since(1.6) 

def var_pop(col): 

""" 

Aggregate function: returns the population variance of the values in a group. 

""" 

return _invoke_function_over_column("var_pop", col) 

 

 

@since(1.6) 

def skewness(col): 

""" 

Aggregate function: returns the skewness of the values in a group. 

""" 

return _invoke_function_over_column("skewness", col) 

 

 

@since(1.6) 

def kurtosis(col): 

""" 

Aggregate function: returns the kurtosis of the values in a group. 

""" 

return _invoke_function_over_column("kurtosis", col) 

 

 

def collect_list(col): 

""" 

Aggregate function: returns a list of objects with duplicates. 

 

.. versionadded:: 1.6.0 

 

Notes 

----- 

The function is non-deterministic because the order of collected results depends 

on the order of the rows which may be non-deterministic after a shuffle. 

 

Examples 

-------- 

>>> df2 = spark.createDataFrame([(2,), (5,), (5,)], ('age',)) 

>>> df2.agg(collect_list('age')).collect() 

[Row(collect_list(age)=[2, 5, 5])] 

""" 

return _invoke_function_over_column("collect_list", col) 

 

 

def collect_set(col): 

""" 

Aggregate function: returns a set of objects with duplicate elements eliminated. 

 

.. versionadded:: 1.6.0 

 

Notes 

----- 

The function is non-deterministic because the order of collected results depends 

on the order of the rows which may be non-deterministic after a shuffle. 

 

Examples 

-------- 

>>> df2 = spark.createDataFrame([(2,), (5,), (5,)], ('age',)) 

>>> df2.agg(collect_set('age')).collect() 

[Row(collect_set(age)=[5, 2])] 

""" 

return _invoke_function_over_column("collect_set", col) 

 

 

def degrees(col): 

""" 

Converts an angle measured in radians to an approximately equivalent angle 

measured in degrees. 

 

.. versionadded:: 2.1.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

angle in radians 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

angle in degrees, as if computed by `java.lang.Math.toDegrees()` 

""" 

return _invoke_function_over_column("degrees", col) 

 

 

def radians(col): 

""" 

Converts an angle measured in degrees to an approximately equivalent angle 

measured in radians. 

 

.. versionadded:: 2.1.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

angle in degrees 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

angle in radians, as if computed by `java.lang.Math.toRadians()` 

""" 

return _invoke_function_over_column("radians", col) 

 

 

def atan2(col1, col2): 

""" 

.. versionadded:: 1.4.0 

 

Parameters 

---------- 

col1 : str, :class:`~pyspark.sql.Column` or float 

coordinate on y-axis 

col2 : str, :class:`~pyspark.sql.Column` or float 

coordinate on x-axis 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

the `theta` component of the point 

(`r`, `theta`) 

in polar coordinates that corresponds to the point 

(`x`, `y`) in Cartesian coordinates, 

as if computed by `java.lang.Math.atan2()` 

""" 

return _invoke_binary_math_function("atan2", col1, col2) 

 

 

@since(1.4) 

def hypot(col1, col2): 

""" 

Computes ``sqrt(a^2 + b^2)`` without intermediate overflow or underflow. 

""" 

return _invoke_binary_math_function("hypot", col1, col2) 

 

 

@since(1.4) 

def pow(col1, col2): 

""" 

Returns the value of the first argument raised to the power of the second argument. 

""" 

return _invoke_binary_math_function("pow", col1, col2) 

 

 

@since(1.6) 

def row_number(): 

""" 

Window function: returns a sequential number starting at 1 within a window partition. 

""" 

return _invoke_function("row_number") 

 

 

@since(1.6) 

def dense_rank(): 

""" 

Window function: returns the rank of rows within a window partition, without any gaps. 

 

The difference between rank and dense_rank is that dense_rank leaves no gaps in ranking 

sequence when there are ties. That is, if you were ranking a competition using dense_rank 

and had three people tie for second place, you would say that all three were in second 

place and that the next person came in third. Rank would give me sequential numbers, making 

the person that came in third place (after the ties) would register as coming in fifth. 

 

This is equivalent to the DENSE_RANK function in SQL. 

""" 

return _invoke_function("dense_rank") 

 

 

@since(1.6) 

def rank(): 

""" 

Window function: returns the rank of rows within a window partition. 

 

The difference between rank and dense_rank is that dense_rank leaves no gaps in ranking 

sequence when there are ties. That is, if you were ranking a competition using dense_rank 

and had three people tie for second place, you would say that all three were in second 

place and that the next person came in third. Rank would give me sequential numbers, making 

the person that came in third place (after the ties) would register as coming in fifth. 

 

This is equivalent to the RANK function in SQL. 

""" 

return _invoke_function("rank") 

 

 

@since(1.6) 

def cume_dist(): 

""" 

Window function: returns the cumulative distribution of values within a window partition, 

i.e. the fraction of rows that are below the current row. 

""" 

return _invoke_function("cume_dist") 

 

 

@since(1.6) 

def percent_rank(): 

""" 

Window function: returns the relative rank (i.e. percentile) of rows within a window partition. 

""" 

return _invoke_function("percent_rank") 

 

 

@since(1.3) 

def approxCountDistinct(col, rsd=None): 

""" 

.. deprecated:: 2.1.0 

Use :func:`approx_count_distinct` instead. 

""" 

warnings.warn("Deprecated in 2.1, use approx_count_distinct instead.", FutureWarning) 

return approx_count_distinct(col, rsd) 

 

 

def approx_count_distinct(col, rsd=None): 

"""Aggregate function: returns a new :class:`~pyspark.sql.Column` for approximate distinct count 

of column `col`. 

 

.. versionadded:: 2.1.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

rsd : float, optional 

maximum relative standard deviation allowed (default = 0.05). 

For rsd < 0.01, it is more efficient to use :func:`count_distinct` 

 

Examples 

-------- 

>>> df.agg(approx_count_distinct(df.age).alias('distinct_ages')).collect() 

[Row(distinct_ages=2)] 

""" 

sc = SparkContext._active_spark_context 

874 ↛ 877line 874 didn't jump to line 877, because the condition on line 874 was never false if rsd is None: 

jc = sc._jvm.functions.approx_count_distinct(_to_java_column(col)) 

else: 

jc = sc._jvm.functions.approx_count_distinct(_to_java_column(col), rsd) 

return Column(jc) 

 

 

@since(1.6) 

def broadcast(df): 

"""Marks a DataFrame as small enough for use in broadcast joins.""" 

 

sc = SparkContext._active_spark_context 

return DataFrame(sc._jvm.functions.broadcast(df._jdf), df.sql_ctx) 

 

 

def coalesce(*cols): 

"""Returns the first column that is not null. 

 

.. versionadded:: 1.4.0 

 

Examples 

-------- 

>>> cDf = spark.createDataFrame([(None, None), (1, None), (None, 2)], ("a", "b")) 

>>> cDf.show() 

+----+----+ 

| a| b| 

+----+----+ 

|null|null| 

| 1|null| 

|null| 2| 

+----+----+ 

 

>>> cDf.select(coalesce(cDf["a"], cDf["b"])).show() 

+--------------+ 

|coalesce(a, b)| 

+--------------+ 

| null| 

| 1| 

| 2| 

+--------------+ 

 

>>> cDf.select('*', coalesce(cDf["a"], lit(0.0))).show() 

+----+----+----------------+ 

| a| b|coalesce(a, 0.0)| 

+----+----+----------------+ 

|null|null| 0.0| 

| 1|null| 1.0| 

|null| 2| 0.0| 

+----+----+----------------+ 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.coalesce(_to_seq(sc, cols, _to_java_column)) 

return Column(jc) 

 

 

def corr(col1, col2): 

"""Returns a new :class:`~pyspark.sql.Column` for the Pearson Correlation Coefficient for 

``col1`` and ``col2``. 

 

.. versionadded:: 1.6.0 

 

Examples 

-------- 

>>> a = range(20) 

>>> b = [2 * x for x in range(20)] 

>>> df = spark.createDataFrame(zip(a, b), ["a", "b"]) 

>>> df.agg(corr("a", "b").alias('c')).collect() 

[Row(c=1.0)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.corr(_to_java_column(col1), _to_java_column(col2))) 

 

 

def covar_pop(col1, col2): 

"""Returns a new :class:`~pyspark.sql.Column` for the population covariance of ``col1`` and 

``col2``. 

 

.. versionadded:: 2.0.0 

 

Examples 

-------- 

>>> a = [1] * 10 

>>> b = [1] * 10 

>>> df = spark.createDataFrame(zip(a, b), ["a", "b"]) 

>>> df.agg(covar_pop("a", "b").alias('c')).collect() 

[Row(c=0.0)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.covar_pop(_to_java_column(col1), _to_java_column(col2))) 

 

 

def covar_samp(col1, col2): 

"""Returns a new :class:`~pyspark.sql.Column` for the sample covariance of ``col1`` and 

``col2``. 

 

.. versionadded:: 2.0.0 

 

Examples 

-------- 

>>> a = [1] * 10 

>>> b = [1] * 10 

>>> df = spark.createDataFrame(zip(a, b), ["a", "b"]) 

>>> df.agg(covar_samp("a", "b").alias('c')).collect() 

[Row(c=0.0)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.covar_samp(_to_java_column(col1), _to_java_column(col2))) 

 

 

def countDistinct(col, *cols): 

"""Returns a new :class:`~pyspark.sql.Column` for distinct count of ``col`` or ``cols``. 

 

An alias of :func:`count_distinct`, and it is encouraged to use :func:`count_distinct` 

directly. 

 

.. versionadded:: 1.3.0 

""" 

return count_distinct(col, *cols) 

 

 

def count_distinct(col, *cols): 

"""Returns a new :class:`Column` for distinct count of ``col`` or ``cols``. 

 

.. versionadded:: 3.2.0 

 

Examples 

-------- 

>>> df.agg(count_distinct(df.age, df.name).alias('c')).collect() 

[Row(c=2)] 

 

>>> df.agg(count_distinct("age", "name").alias('c')).collect() 

[Row(c=2)] 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.count_distinct(_to_java_column(col), _to_seq(sc, cols, _to_java_column)) 

return Column(jc) 

 

 

def first(col, ignorenulls=False): 

"""Aggregate function: returns the first value in a group. 

 

The function by default returns the first values it sees. It will return the first non-null 

value it sees when ignoreNulls is set to true. If all values are null, then null is returned. 

 

.. versionadded:: 1.3.0 

 

Notes 

----- 

The function is non-deterministic because its results depends on the order of the 

rows which may be non-deterministic after a shuffle. 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.first(_to_java_column(col), ignorenulls) 

return Column(jc) 

 

 

def grouping(col): 

""" 

Aggregate function: indicates whether a specified column in a GROUP BY list is aggregated 

or not, returns 1 for aggregated or 0 for not aggregated in the result set. 

 

.. versionadded:: 2.0.0 

 

Examples 

-------- 

>>> df.cube("name").agg(grouping("name"), sum("age")).orderBy("name").show() 

+-----+--------------+--------+ 

| name|grouping(name)|sum(age)| 

+-----+--------------+--------+ 

| null| 1| 7| 

|Alice| 0| 2| 

| Bob| 0| 5| 

+-----+--------------+--------+ 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.grouping(_to_java_column(col)) 

return Column(jc) 

 

 

def grouping_id(*cols): 

""" 

Aggregate function: returns the level of grouping, equals to 

 

(grouping(c1) << (n-1)) + (grouping(c2) << (n-2)) + ... + grouping(cn) 

 

.. versionadded:: 2.0.0 

 

Notes 

----- 

The list of columns should match with grouping columns exactly, or empty (means all 

the grouping columns). 

 

Examples 

-------- 

>>> df.cube("name").agg(grouping_id(), sum("age")).orderBy("name").show() 

+-----+-------------+--------+ 

| name|grouping_id()|sum(age)| 

+-----+-------------+--------+ 

| null| 1| 7| 

|Alice| 0| 2| 

| Bob| 0| 5| 

+-----+-------------+--------+ 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.grouping_id(_to_seq(sc, cols, _to_java_column)) 

return Column(jc) 

 

 

@since(1.6) 

def input_file_name(): 

"""Creates a string column for the file name of the current Spark task. 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.input_file_name()) 

 

 

def isnan(col): 

"""An expression that returns true iff the column is NaN. 

 

.. versionadded:: 1.6.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(1.0, float('nan')), (float('nan'), 2.0)], ("a", "b")) 

>>> df.select(isnan("a").alias("r1"), isnan(df.a).alias("r2")).collect() 

[Row(r1=False, r2=False), Row(r1=True, r2=True)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.isnan(_to_java_column(col))) 

 

 

def isnull(col): 

"""An expression that returns true iff the column is null. 

 

.. versionadded:: 1.6.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(1, None), (None, 2)], ("a", "b")) 

>>> df.select(isnull("a").alias("r1"), isnull(df.a).alias("r2")).collect() 

[Row(r1=False, r2=False), Row(r1=True, r2=True)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.isnull(_to_java_column(col))) 

 

 

def last(col, ignorenulls=False): 

"""Aggregate function: returns the last value in a group. 

 

The function by default returns the last values it sees. It will return the last non-null 

value it sees when ignoreNulls is set to true. If all values are null, then null is returned. 

 

.. versionadded:: 1.3.0 

 

Notes 

----- 

The function is non-deterministic because its results depends on the order of the 

rows which may be non-deterministic after a shuffle. 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.last(_to_java_column(col), ignorenulls) 

return Column(jc) 

 

 

def monotonically_increasing_id(): 

"""A column that generates monotonically increasing 64-bit integers. 

 

The generated ID is guaranteed to be monotonically increasing and unique, but not consecutive. 

The current implementation puts the partition ID in the upper 31 bits, and the record number 

within each partition in the lower 33 bits. The assumption is that the data frame has 

less than 1 billion partitions, and each partition has less than 8 billion records. 

 

.. versionadded:: 1.6.0 

 

Notes 

----- 

The function is non-deterministic because its result depends on partition IDs. 

 

As an example, consider a :class:`DataFrame` with two partitions, each with 3 records. 

This expression would return the following IDs: 

0, 1, 2, 8589934592 (1L << 33), 8589934593, 8589934594. 

 

>>> df0 = sc.parallelize(range(2), 2).mapPartitions(lambda x: [(1,), (2,), (3,)]).toDF(['col1']) 

>>> df0.select(monotonically_increasing_id().alias('id')).collect() 

[Row(id=0), Row(id=1), Row(id=2), Row(id=8589934592), Row(id=8589934593), Row(id=8589934594)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.monotonically_increasing_id()) 

 

 

def nanvl(col1, col2): 

"""Returns col1 if it is not NaN, or col2 if col1 is NaN. 

 

Both inputs should be floating point columns (:class:`DoubleType` or :class:`FloatType`). 

 

.. versionadded:: 1.6.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(1.0, float('nan')), (float('nan'), 2.0)], ("a", "b")) 

>>> df.select(nanvl("a", "b").alias("r1"), nanvl(df.a, df.b).alias("r2")).collect() 

[Row(r1=1.0, r2=1.0), Row(r1=2.0, r2=2.0)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.nanvl(_to_java_column(col1), _to_java_column(col2))) 

 

 

def percentile_approx(col, percentage, accuracy=10000): 

"""Returns the approximate `percentile` of the numeric column `col` which is the smallest value 

in the ordered `col` values (sorted from least to greatest) such that no more than `percentage` 

of `col` values is less than the value or equal to that value. 

The value of percentage must be between 0.0 and 1.0. 

 

The accuracy parameter (default: 10000) 

is a positive numeric literal which controls approximation accuracy at the cost of memory. 

Higher value of accuracy yields better accuracy, 1.0/accuracy is the relative error 

of the approximation. 

 

When percentage is an array, each value of the percentage array must be between 0.0 and 1.0. 

In this case, returns the approximate percentile array of column col 

at the given percentage array. 

 

.. versionadded:: 3.1.0 

 

Examples 

-------- 

>>> key = (col("id") % 3).alias("key") 

>>> value = (randn(42) + key * 10).alias("value") 

>>> df = spark.range(0, 1000, 1, 1).select(key, value) 

>>> df.select( 

... percentile_approx("value", [0.25, 0.5, 0.75], 1000000).alias("quantiles") 

... ).printSchema() 

root 

|-- quantiles: array (nullable = true) 

| |-- element: double (containsNull = false) 

 

>>> df.groupBy("key").agg( 

... percentile_approx("value", 0.5, lit(1000000)).alias("median") 

... ).printSchema() 

root 

|-- key: long (nullable = true) 

|-- median: double (nullable = true) 

""" 

sc = SparkContext._active_spark_context 

 

if isinstance(percentage, (list, tuple)): 

# A local list 

percentage = sc._jvm.functions.array(_to_seq(sc, [ 

_create_column_from_literal(x) for x in percentage 

])) 

elif isinstance(percentage, Column): 

# Already a Column 

percentage = _to_java_column(percentage) 

else: 

# Probably scalar 

percentage = _create_column_from_literal(percentage) 

 

accuracy = ( 

_to_java_column(accuracy) if isinstance(accuracy, Column) 

else _create_column_from_literal(accuracy) 

) 

 

return Column(sc._jvm.functions.percentile_approx(_to_java_column(col), percentage, accuracy)) 

 

 

def rand(seed=None): 

"""Generates a random column with independent and identically distributed (i.i.d.) samples 

uniformly distributed in [0.0, 1.0). 

 

.. versionadded:: 1.4.0 

 

Notes 

----- 

The function is non-deterministic in general case. 

 

Examples 

-------- 

>>> df.withColumn('rand', rand(seed=42) * 3).collect() 

[Row(age=2, name='Alice', rand=2.4052597283576684), 

Row(age=5, name='Bob', rand=2.3913904055683974)] 

""" 

sc = SparkContext._active_spark_context 

if seed is not None: 

jc = sc._jvm.functions.rand(seed) 

else: 

jc = sc._jvm.functions.rand() 

return Column(jc) 

 

 

def randn(seed=None): 

"""Generates a column with independent and identically distributed (i.i.d.) samples from 

the standard normal distribution. 

 

.. versionadded:: 1.4.0 

 

Notes 

----- 

The function is non-deterministic in general case. 

 

Examples 

-------- 

>>> df.withColumn('randn', randn(seed=42)).collect() 

[Row(age=2, name='Alice', randn=1.1027054481455365), 

Row(age=5, name='Bob', randn=0.7400395449950132)] 

""" 

sc = SparkContext._active_spark_context 

1280 ↛ 1283line 1280 didn't jump to line 1283, because the condition on line 1280 was never false if seed is not None: 

jc = sc._jvm.functions.randn(seed) 

else: 

jc = sc._jvm.functions.randn() 

return Column(jc) 

 

 

def round(col, scale=0): 

""" 

Round the given value to `scale` decimal places using HALF_UP rounding mode if `scale` >= 0 

or at integral part when `scale` < 0. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> spark.createDataFrame([(2.5,)], ['a']).select(round('a', 0).alias('r')).collect() 

[Row(r=3.0)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.round(_to_java_column(col), scale)) 

 

 

def bround(col, scale=0): 

""" 

Round the given value to `scale` decimal places using HALF_EVEN rounding mode if `scale` >= 0 

or at integral part when `scale` < 0. 

 

.. versionadded:: 2.0.0 

 

Examples 

-------- 

>>> spark.createDataFrame([(2.5,)], ['a']).select(bround('a', 0).alias('r')).collect() 

[Row(r=2.0)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.bround(_to_java_column(col), scale)) 

 

 

def shiftLeft(col, numBits): 

"""Shift the given value numBits left. 

 

.. versionadded:: 1.5.0 

 

.. deprecated:: 3.2.0 

Use :func:`shiftleft` instead. 

""" 

warnings.warn("Deprecated in 3.2, use shiftleft instead.", FutureWarning) 

return shiftleft(col, numBits) 

 

 

def shiftleft(col, numBits): 

"""Shift the given value numBits left. 

 

.. versionadded:: 3.2.0 

 

Examples 

-------- 

>>> spark.createDataFrame([(21,)], ['a']).select(shiftleft('a', 1).alias('r')).collect() 

[Row(r=42)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.shiftleft(_to_java_column(col), numBits)) 

 

 

def shiftRight(col, numBits): 

"""(Signed) shift the given value numBits right. 

 

.. versionadded:: 1.5.0 

 

.. deprecated:: 3.2.0 

Use :func:`shiftright` instead. 

""" 

warnings.warn("Deprecated in 3.2, use shiftright instead.", FutureWarning) 

return shiftright(col, numBits) 

 

 

def shiftright(col, numBits): 

"""(Signed) shift the given value numBits right. 

 

.. versionadded:: 3.2.0 

 

Examples 

-------- 

>>> spark.createDataFrame([(42,)], ['a']).select(shiftright('a', 1).alias('r')).collect() 

[Row(r=21)] 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.shiftRight(_to_java_column(col), numBits) 

return Column(jc) 

 

 

def shiftRightUnsigned(col, numBits): 

"""Unsigned shift the given value numBits right. 

 

.. versionadded:: 1.5.0 

 

.. deprecated:: 3.2.0 

Use :func:`shiftrightunsigned` instead. 

""" 

warnings.warn("Deprecated in 3.2, use shiftrightunsigned instead.", FutureWarning) 

return shiftrightunsigned(col, numBits) 

 

 

def shiftrightunsigned(col, numBits): 

"""Unsigned shift the given value numBits right. 

 

.. versionadded:: 3.2.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(-42,)], ['a']) 

>>> df.select(shiftrightunsigned('a', 1).alias('r')).collect() 

[Row(r=9223372036854775787)] 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.shiftRightUnsigned(_to_java_column(col), numBits) 

return Column(jc) 

 

 

def spark_partition_id(): 

"""A column for partition ID. 

 

.. versionadded:: 1.6.0 

 

Notes 

----- 

This is non deterministic because it depends on data partitioning and task scheduling. 

 

Examples 

-------- 

>>> df.repartition(1).select(spark_partition_id().alias("pid")).collect() 

[Row(pid=0), Row(pid=0)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.spark_partition_id()) 

 

 

def expr(str): 

"""Parses the expression string into the column that it represents 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df.select(expr("length(name)")).collect() 

[Row(length(name)=5), Row(length(name)=3)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.expr(str)) 

 

 

def struct(*cols): 

"""Creates a new struct column. 

 

.. versionadded:: 1.4.0 

 

Parameters 

---------- 

cols : list, set, str or :class:`~pyspark.sql.Column` 

column names or :class:`~pyspark.sql.Column`\\s to contain in the output struct. 

 

Examples 

-------- 

>>> df.select(struct('age', 'name').alias("struct")).collect() 

[Row(struct=Row(age=2, name='Alice')), Row(struct=Row(age=5, name='Bob'))] 

>>> df.select(struct([df.age, df.name]).alias("struct")).collect() 

[Row(struct=Row(age=2, name='Alice')), Row(struct=Row(age=5, name='Bob'))] 

""" 

sc = SparkContext._active_spark_context 

if len(cols) == 1 and isinstance(cols[0], (list, set)): 

cols = cols[0] 

jc = sc._jvm.functions.struct(_to_seq(sc, cols, _to_java_column)) 

return Column(jc) 

 

 

def greatest(*cols): 

""" 

Returns the greatest value of the list of column names, skipping null values. 

This function takes at least 2 parameters. It will return null iff all parameters are null. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(1, 4, 3)], ['a', 'b', 'c']) 

>>> df.select(greatest(df.a, df.b, df.c).alias("greatest")).collect() 

[Row(greatest=4)] 

""" 

1469 ↛ 1470line 1469 didn't jump to line 1470, because the condition on line 1469 was never true if len(cols) < 2: 

raise ValueError("greatest should take at least two columns") 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.greatest(_to_seq(sc, cols, _to_java_column))) 

 

 

def least(*cols): 

""" 

Returns the least value of the list of column names, skipping null values. 

This function takes at least 2 parameters. It will return null iff all parameters are null. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(1, 4, 3)], ['a', 'b', 'c']) 

>>> df.select(least(df.a, df.b, df.c).alias("least")).collect() 

[Row(least=1)] 

""" 

1488 ↛ 1489line 1488 didn't jump to line 1489, because the condition on line 1488 was never true if len(cols) < 2: 

raise ValueError("least should take at least two columns") 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.least(_to_seq(sc, cols, _to_java_column))) 

 

 

def when(condition, value): 

"""Evaluates a list of conditions and returns one of multiple possible result expressions. 

If :func:`pyspark.sql.Column.otherwise` is not invoked, None is returned for unmatched 

conditions. 

 

.. versionadded:: 1.4.0 

 

Parameters 

---------- 

condition : :class:`~pyspark.sql.Column` 

a boolean :class:`~pyspark.sql.Column` expression. 

value : 

a literal value, or a :class:`~pyspark.sql.Column` expression. 

 

>>> df.select(when(df['age'] == 2, 3).otherwise(4).alias("age")).collect() 

[Row(age=3), Row(age=4)] 

 

>>> df.select(when(df.age == 2, df.age + 1).alias("age")).collect() 

[Row(age=3), Row(age=None)] 

""" 

sc = SparkContext._active_spark_context 

1515 ↛ 1516line 1515 didn't jump to line 1516, because the condition on line 1515 was never true if not isinstance(condition, Column): 

raise TypeError("condition should be a Column") 

v = value._jc if isinstance(value, Column) else value 

jc = sc._jvm.functions.when(condition._jc, v) 

return Column(jc) 

 

 

def log(arg1, arg2=None): 

"""Returns the first argument-based logarithm of the second argument. 

 

If there is only one argument, then this takes the natural logarithm of the argument. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df.select(log(10.0, df.age).alias('ten')).rdd.map(lambda l: str(l.ten)[:7]).collect() 

['0.30102', '0.69897'] 

 

>>> df.select(log(df.age).alias('e')).rdd.map(lambda l: str(l.e)[:7]).collect() 

['0.69314', '1.60943'] 

""" 

sc = SparkContext._active_spark_context 

if arg2 is None: 

jc = sc._jvm.functions.log(_to_java_column(arg1)) 

else: 

jc = sc._jvm.functions.log(arg1, _to_java_column(arg2)) 

return Column(jc) 

 

 

def log2(col): 

"""Returns the base-2 logarithm of the argument. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> spark.createDataFrame([(4,)], ['a']).select(log2('a').alias('log2')).collect() 

[Row(log2=2.0)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.log2(_to_java_column(col))) 

 

 

def conv(col, fromBase, toBase): 

""" 

Convert a number in a string column from one base to another. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([("010101",)], ['n']) 

>>> df.select(conv(df.n, 2, 16).alias('hex')).collect() 

[Row(hex='15')] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.conv(_to_java_column(col), fromBase, toBase)) 

 

 

def factorial(col): 

""" 

Computes the factorial of the given value. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(5,)], ['n']) 

>>> df.select(factorial(df.n).alias('f')).collect() 

[Row(f=120)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.factorial(_to_java_column(col))) 

 

 

# --------------- Window functions ------------------------ 

 

def lag(col, offset=1, default=None): 

""" 

Window function: returns the value that is `offset` rows before the current row, and 

`default` if there is less than `offset` rows before the current row. For example, 

an `offset` of one will return the previous row at any given point in the window partition. 

 

This is equivalent to the LAG function in SQL. 

 

.. versionadded:: 1.4.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

offset : int, optional 

number of row to extend 

default : optional 

default value 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.lag(_to_java_column(col), offset, default)) 

 

 

def lead(col, offset=1, default=None): 

""" 

Window function: returns the value that is `offset` rows after the current row, and 

`default` if there is less than `offset` rows after the current row. For example, 

an `offset` of one will return the next row at any given point in the window partition. 

 

This is equivalent to the LEAD function in SQL. 

 

.. versionadded:: 1.4.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

offset : int, optional 

number of row to extend 

default : optional 

default value 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.lead(_to_java_column(col), offset, default)) 

 

 

def nth_value(col, offset, ignoreNulls=False): 

""" 

Window function: returns the value that is the `offset`\\th row of the window frame 

(counting from 1), and `null` if the size of window frame is less than `offset` rows. 

 

It will return the `offset`\\th non-null value it sees when `ignoreNulls` is set to 

true. If all values are null, then null is returned. 

 

This is equivalent to the nth_value function in SQL. 

 

.. versionadded:: 3.1.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

offset : int, optional 

number of row to use as the value 

ignoreNulls : bool, optional 

indicates the Nth value should skip null in the 

determination of which row to use 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.nth_value(_to_java_column(col), offset, ignoreNulls)) 

 

 

def ntile(n): 

""" 

Window function: returns the ntile group id (from 1 to `n` inclusive) 

in an ordered window partition. For example, if `n` is 4, the first 

quarter of the rows will get value 1, the second quarter will get 2, 

the third quarter will get 3, and the last quarter will get 4. 

 

This is equivalent to the NTILE function in SQL. 

 

.. versionadded:: 1.4.0 

 

Parameters 

---------- 

n : int 

an integer 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.ntile(int(n))) 

 

 

# ---------------------- Date/Timestamp functions ------------------------------ 

 

@since(1.5) 

def current_date(): 

""" 

Returns the current date at the start of query evaluation as a :class:`DateType` column. 

All calls of current_date within the same query return the same value. 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.current_date()) 

 

 

def current_timestamp(): 

""" 

Returns the current timestamp at the start of query evaluation as a :class:`TimestampType` 

column. All calls of current_timestamp within the same query return the same value. 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.current_timestamp()) 

 

 

def date_format(date, format): 

""" 

Converts a date/timestamp/string to a value of string in the format specified by the date 

format given by the second argument. 

 

A pattern could be for instance `dd.MM.yyyy` and could return a string like '18.03.1993'. All 

pattern letters of `datetime pattern`_. can be used. 

 

.. _datetime pattern: https://spark.apache.org/docs/latest/sql-ref-datetime-pattern.html 

 

.. versionadded:: 1.5.0 

 

Notes 

----- 

Whenever possible, use specialized functions like `year`. 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) 

>>> df.select(date_format('dt', 'MM/dd/yyy').alias('date')).collect() 

[Row(date='04/08/2015')] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.date_format(_to_java_column(date), format)) 

 

 

def year(col): 

""" 

Extract the year of a given date as integer. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) 

>>> df.select(year('dt').alias('year')).collect() 

[Row(year=2015)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.year(_to_java_column(col))) 

 

 

def quarter(col): 

""" 

Extract the quarter of a given date as integer. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) 

>>> df.select(quarter('dt').alias('quarter')).collect() 

[Row(quarter=2)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.quarter(_to_java_column(col))) 

 

 

def month(col): 

""" 

Extract the month of a given date as integer. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) 

>>> df.select(month('dt').alias('month')).collect() 

[Row(month=4)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.month(_to_java_column(col))) 

 

 

def dayofweek(col): 

""" 

Extract the day of the week of a given date as integer. 

Ranges from 1 for a Sunday through to 7 for a Saturday 

 

.. versionadded:: 2.3.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) 

>>> df.select(dayofweek('dt').alias('day')).collect() 

[Row(day=4)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.dayofweek(_to_java_column(col))) 

 

 

def dayofmonth(col): 

""" 

Extract the day of the month of a given date as integer. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) 

>>> df.select(dayofmonth('dt').alias('day')).collect() 

[Row(day=8)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.dayofmonth(_to_java_column(col))) 

 

 

def dayofyear(col): 

""" 

Extract the day of the year of a given date as integer. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) 

>>> df.select(dayofyear('dt').alias('day')).collect() 

[Row(day=98)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.dayofyear(_to_java_column(col))) 

 

 

def hour(col): 

""" 

Extract the hours of a given date as integer. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('2015-04-08 13:08:15',)], ['ts']) 

>>> df.select(hour('ts').alias('hour')).collect() 

[Row(hour=13)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.hour(_to_java_column(col))) 

 

 

def minute(col): 

""" 

Extract the minutes of a given date as integer. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('2015-04-08 13:08:15',)], ['ts']) 

>>> df.select(minute('ts').alias('minute')).collect() 

[Row(minute=8)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.minute(_to_java_column(col))) 

 

 

def second(col): 

""" 

Extract the seconds of a given date as integer. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('2015-04-08 13:08:15',)], ['ts']) 

>>> df.select(second('ts').alias('second')).collect() 

[Row(second=15)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.second(_to_java_column(col))) 

 

 

def weekofyear(col): 

""" 

Extract the week number of a given date as integer. 

A week is considered to start on a Monday and week 1 is the first week with more than 3 days, 

as defined by ISO 8601 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) 

>>> df.select(weekofyear(df.dt).alias('week')).collect() 

[Row(week=15)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.weekofyear(_to_java_column(col))) 

 

 

def date_add(start, days): 

""" 

Returns the date that is `days` days after `start` 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) 

>>> df.select(date_add(df.dt, 1).alias('next_date')).collect() 

[Row(next_date=datetime.date(2015, 4, 9))] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.date_add(_to_java_column(start), days)) 

 

 

def date_sub(start, days): 

""" 

Returns the date that is `days` days before `start` 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) 

>>> df.select(date_sub(df.dt, 1).alias('prev_date')).collect() 

[Row(prev_date=datetime.date(2015, 4, 7))] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.date_sub(_to_java_column(start), days)) 

 

 

def datediff(end, start): 

""" 

Returns the number of days from `start` to `end`. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('2015-04-08','2015-05-10')], ['d1', 'd2']) 

>>> df.select(datediff(df.d2, df.d1).alias('diff')).collect() 

[Row(diff=32)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.datediff(_to_java_column(end), _to_java_column(start))) 

 

 

def add_months(start, months): 

""" 

Returns the date that is `months` months after `start` 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('2015-04-08',)], ['dt']) 

>>> df.select(add_months(df.dt, 1).alias('next_month')).collect() 

[Row(next_month=datetime.date(2015, 5, 8))] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.add_months(_to_java_column(start), months)) 

 

 

def months_between(date1, date2, roundOff=True): 

""" 

Returns number of months between dates date1 and date2. 

If date1 is later than date2, then the result is positive. 

A whole number is returned if both inputs have the same day of month or both are the last day 

of their respective months. Otherwise, the difference is calculated assuming 31 days per month. 

The result is rounded off to 8 digits unless `roundOff` is set to `False`. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('1997-02-28 10:30:00', '1996-10-30')], ['date1', 'date2']) 

>>> df.select(months_between(df.date1, df.date2).alias('months')).collect() 

[Row(months=3.94959677)] 

>>> df.select(months_between(df.date1, df.date2, False).alias('months')).collect() 

[Row(months=3.9495967741935485)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.months_between( 

_to_java_column(date1), _to_java_column(date2), roundOff)) 

 

 

def to_date(col, format=None): 

"""Converts a :class:`~pyspark.sql.Column` into :class:`pyspark.sql.types.DateType` 

using the optionally specified format. Specify formats according to `datetime pattern`_. 

By default, it follows casting rules to :class:`pyspark.sql.types.DateType` if the format 

is omitted. Equivalent to ``col.cast("date")``. 

 

.. _datetime pattern: https://spark.apache.org/docs/latest/sql-ref-datetime-pattern.html 

 

.. versionadded:: 2.2.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t']) 

>>> df.select(to_date(df.t).alias('date')).collect() 

[Row(date=datetime.date(1997, 2, 28))] 

 

>>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t']) 

>>> df.select(to_date(df.t, 'yyyy-MM-dd HH:mm:ss').alias('date')).collect() 

[Row(date=datetime.date(1997, 2, 28))] 

""" 

sc = SparkContext._active_spark_context 

if format is None: 

jc = sc._jvm.functions.to_date(_to_java_column(col)) 

else: 

jc = sc._jvm.functions.to_date(_to_java_column(col), format) 

return Column(jc) 

 

 

def to_timestamp(col, format=None): 

"""Converts a :class:`~pyspark.sql.Column` into :class:`pyspark.sql.types.TimestampType` 

using the optionally specified format. Specify formats according to `datetime pattern`_. 

By default, it follows casting rules to :class:`pyspark.sql.types.TimestampType` if the format 

is omitted. Equivalent to ``col.cast("timestamp")``. 

 

.. _datetime pattern: https://spark.apache.org/docs/latest/sql-ref-datetime-pattern.html 

 

.. versionadded:: 2.2.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t']) 

>>> df.select(to_timestamp(df.t).alias('dt')).collect() 

[Row(dt=datetime.datetime(1997, 2, 28, 10, 30))] 

 

>>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t']) 

>>> df.select(to_timestamp(df.t, 'yyyy-MM-dd HH:mm:ss').alias('dt')).collect() 

[Row(dt=datetime.datetime(1997, 2, 28, 10, 30))] 

""" 

sc = SparkContext._active_spark_context 

if format is None: 

jc = sc._jvm.functions.to_timestamp(_to_java_column(col)) 

else: 

jc = sc._jvm.functions.to_timestamp(_to_java_column(col), format) 

return Column(jc) 

 

 

def trunc(date, format): 

""" 

Returns date truncated to the unit specified by the format. 

 

.. versionadded:: 1.5.0 

 

Parameters 

---------- 

date : :class:`~pyspark.sql.Column` or str 

format : str 

'year', 'yyyy', 'yy' to truncate by year, 

or 'month', 'mon', 'mm' to truncate by month 

Other options are: 'week', 'quarter' 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('1997-02-28',)], ['d']) 

>>> df.select(trunc(df.d, 'year').alias('year')).collect() 

[Row(year=datetime.date(1997, 1, 1))] 

>>> df.select(trunc(df.d, 'mon').alias('month')).collect() 

[Row(month=datetime.date(1997, 2, 1))] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.trunc(_to_java_column(date), format)) 

 

 

def date_trunc(format, timestamp): 

""" 

Returns timestamp truncated to the unit specified by the format. 

 

.. versionadded:: 2.3.0 

 

Parameters 

---------- 

format : str 

'year', 'yyyy', 'yy' to truncate by year, 

'month', 'mon', 'mm' to truncate by month, 

'day', 'dd' to truncate by day, 

Other options are: 

'microsecond', 'millisecond', 'second', 'minute', 'hour', 'week', 'quarter' 

timestamp : :class:`~pyspark.sql.Column` or str 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('1997-02-28 05:02:11',)], ['t']) 

>>> df.select(date_trunc('year', df.t).alias('year')).collect() 

[Row(year=datetime.datetime(1997, 1, 1, 0, 0))] 

>>> df.select(date_trunc('mon', df.t).alias('month')).collect() 

[Row(month=datetime.datetime(1997, 2, 1, 0, 0))] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.date_trunc(format, _to_java_column(timestamp))) 

 

 

def next_day(date, dayOfWeek): 

""" 

Returns the first date which is later than the value of the date column. 

 

Day of the week parameter is case insensitive, and accepts: 

"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun". 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('2015-07-27',)], ['d']) 

>>> df.select(next_day(df.d, 'Sun').alias('date')).collect() 

[Row(date=datetime.date(2015, 8, 2))] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.next_day(_to_java_column(date), dayOfWeek)) 

 

 

def last_day(date): 

""" 

Returns the last day of the month which the given date belongs to. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('1997-02-10',)], ['d']) 

>>> df.select(last_day(df.d).alias('date')).collect() 

[Row(date=datetime.date(1997, 2, 28))] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.last_day(_to_java_column(date))) 

 

 

def from_unixtime(timestamp, format="yyyy-MM-dd HH:mm:ss"): 

""" 

Converts the number of seconds from unix epoch (1970-01-01 00:00:00 UTC) to a string 

representing the timestamp of that moment in the current system time zone in the given 

format. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> spark.conf.set("spark.sql.session.timeZone", "America/Los_Angeles") 

>>> time_df = spark.createDataFrame([(1428476400,)], ['unix_time']) 

>>> time_df.select(from_unixtime('unix_time').alias('ts')).collect() 

[Row(ts='2015-04-08 00:00:00')] 

>>> spark.conf.unset("spark.sql.session.timeZone") 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.from_unixtime(_to_java_column(timestamp), format)) 

 

 

def unix_timestamp(timestamp=None, format='yyyy-MM-dd HH:mm:ss'): 

""" 

Convert time string with given pattern ('yyyy-MM-dd HH:mm:ss', by default) 

to Unix time stamp (in seconds), using the default timezone and the default 

locale, return null if fail. 

 

if `timestamp` is None, then it returns current timestamp. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> spark.conf.set("spark.sql.session.timeZone", "America/Los_Angeles") 

>>> time_df = spark.createDataFrame([('2015-04-08',)], ['dt']) 

>>> time_df.select(unix_timestamp('dt', 'yyyy-MM-dd').alias('unix_time')).collect() 

[Row(unix_time=1428476400)] 

>>> spark.conf.unset("spark.sql.session.timeZone") 

""" 

sc = SparkContext._active_spark_context 

2166 ↛ 2167line 2166 didn't jump to line 2167, because the condition on line 2166 was never true if timestamp is None: 

return Column(sc._jvm.functions.unix_timestamp()) 

return Column(sc._jvm.functions.unix_timestamp(_to_java_column(timestamp), format)) 

 

 

def from_utc_timestamp(timestamp, tz): 

""" 

This is a common function for databases supporting TIMESTAMP WITHOUT TIMEZONE. This function 

takes a timestamp which is timezone-agnostic, and interprets it as a timestamp in UTC, and 

renders that timestamp as a timestamp in the given time zone. 

 

However, timestamp in Spark represents number of microseconds from the Unix epoch, which is not 

timezone-agnostic. So in Spark this function just shift the timestamp value from UTC timezone to 

the given timezone. 

 

This function may return confusing result if the input is a string with timezone, e.g. 

'2018-03-13T06:18:23+00:00'. The reason is that, Spark firstly cast the string to timestamp 

according to the timezone in the string, and finally display the result by converting the 

timestamp to string according to the session local timezone. 

 

.. versionadded:: 1.5.0 

 

Parameters 

---------- 

timestamp : :class:`~pyspark.sql.Column` or str 

the column that contains timestamps 

tz : :class:`~pyspark.sql.Column` or str 

A string detailing the time zone ID that the input should be adjusted to. It should 

be in the format of either region-based zone IDs or zone offsets. Region IDs must 

have the form 'area/city', such as 'America/Los_Angeles'. Zone offsets must be in 

the format '(+|-)HH:mm', for example '-08:00' or '+01:00'. Also 'UTC' and 'Z' are 

supported as aliases of '+00:00'. Other short names are not recommended to use 

because they can be ambiguous. 

 

.. versionchanged:: 2.4 

`tz` can take a :class:`~pyspark.sql.Column` containing timezone ID strings. 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('1997-02-28 10:30:00', 'JST')], ['ts', 'tz']) 

>>> df.select(from_utc_timestamp(df.ts, "PST").alias('local_time')).collect() 

[Row(local_time=datetime.datetime(1997, 2, 28, 2, 30))] 

>>> df.select(from_utc_timestamp(df.ts, df.tz).alias('local_time')).collect() 

[Row(local_time=datetime.datetime(1997, 2, 28, 19, 30))] 

""" 

sc = SparkContext._active_spark_context 

if isinstance(tz, Column): 

tz = _to_java_column(tz) 

return Column(sc._jvm.functions.from_utc_timestamp(_to_java_column(timestamp), tz)) 

 

 

def to_utc_timestamp(timestamp, tz): 

""" 

This is a common function for databases supporting TIMESTAMP WITHOUT TIMEZONE. This function 

takes a timestamp which is timezone-agnostic, and interprets it as a timestamp in the given 

timezone, and renders that timestamp as a timestamp in UTC. 

 

However, timestamp in Spark represents number of microseconds from the Unix epoch, which is not 

timezone-agnostic. So in Spark this function just shift the timestamp value from the given 

timezone to UTC timezone. 

 

This function may return confusing result if the input is a string with timezone, e.g. 

'2018-03-13T06:18:23+00:00'. The reason is that, Spark firstly cast the string to timestamp 

according to the timezone in the string, and finally display the result by converting the 

timestamp to string according to the session local timezone. 

 

.. versionadded:: 1.5.0 

 

Parameters 

---------- 

timestamp : :class:`~pyspark.sql.Column` or str 

the column that contains timestamps 

tz : :class:`~pyspark.sql.Column` or str 

A string detailing the time zone ID that the input should be adjusted to. It should 

be in the format of either region-based zone IDs or zone offsets. Region IDs must 

have the form 'area/city', such as 'America/Los_Angeles'. Zone offsets must be in 

the format '(+|-)HH:mm', for example '-08:00' or '+01:00'. Also 'UTC' and 'Z' are 

upported as aliases of '+00:00'. Other short names are not recommended to use 

because they can be ambiguous. 

 

.. versionchanged:: 2.4.0 

`tz` can take a :class:`~pyspark.sql.Column` containing timezone ID strings. 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('1997-02-28 10:30:00', 'JST')], ['ts', 'tz']) 

>>> df.select(to_utc_timestamp(df.ts, "PST").alias('utc_time')).collect() 

[Row(utc_time=datetime.datetime(1997, 2, 28, 18, 30))] 

>>> df.select(to_utc_timestamp(df.ts, df.tz).alias('utc_time')).collect() 

[Row(utc_time=datetime.datetime(1997, 2, 28, 1, 30))] 

""" 

sc = SparkContext._active_spark_context 

if isinstance(tz, Column): 

tz = _to_java_column(tz) 

return Column(sc._jvm.functions.to_utc_timestamp(_to_java_column(timestamp), tz)) 

 

 

def timestamp_seconds(col): 

""" 

.. versionadded:: 3.1.0 

 

Examples 

-------- 

>>> from pyspark.sql.functions import timestamp_seconds 

>>> spark.conf.set("spark.sql.session.timeZone", "America/Los_Angeles") 

>>> time_df = spark.createDataFrame([(1230219000,)], ['unix_time']) 

>>> time_df.select(timestamp_seconds(time_df.unix_time).alias('ts')).show() 

+-------------------+ 

| ts| 

+-------------------+ 

|2008-12-25 07:30:00| 

+-------------------+ 

>>> spark.conf.unset("spark.sql.session.timeZone") 

""" 

 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.timestamp_seconds(_to_java_column(col))) 

 

 

def window(timeColumn, windowDuration, slideDuration=None, startTime=None): 

"""Bucketize rows into one or more time windows given a timestamp specifying column. Window 

starts are inclusive but the window ends are exclusive, e.g. 12:05 will be in the window 

[12:05,12:10) but not in [12:00,12:05). Windows can support microsecond precision. Windows in 

the order of months are not supported. 

 

The time column must be of :class:`pyspark.sql.types.TimestampType`. 

 

Durations are provided as strings, e.g. '1 second', '1 day 12 hours', '2 minutes'. Valid 

interval strings are 'week', 'day', 'hour', 'minute', 'second', 'millisecond', 'microsecond'. 

If the ``slideDuration`` is not provided, the windows will be tumbling windows. 

 

The startTime is the offset with respect to 1970-01-01 00:00:00 UTC with which to start 

window intervals. For example, in order to have hourly tumbling windows that start 15 minutes 

past the hour, e.g. 12:15-13:15, 13:15-14:15... provide `startTime` as `15 minutes`. 

 

The output column will be a struct called 'window' by default with the nested columns 'start' 

and 'end', where 'start' and 'end' will be of :class:`pyspark.sql.types.TimestampType`. 

 

.. versionadded:: 2.0.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([("2016-03-11 09:00:07", 1)]).toDF("date", "val") 

>>> w = df.groupBy(window("date", "5 seconds")).agg(sum("val").alias("sum")) 

>>> w.select(w.window.start.cast("string").alias("start"), 

... w.window.end.cast("string").alias("end"), "sum").collect() 

[Row(start='2016-03-11 09:00:05', end='2016-03-11 09:00:10', sum=1)] 

""" 

def check_string_field(field, fieldName): 

2315 ↛ 2316line 2315 didn't jump to line 2316, because the condition on line 2315 was never true if not field or type(field) is not str: 

raise TypeError("%s should be provided as a string" % fieldName) 

 

sc = SparkContext._active_spark_context 

time_col = _to_java_column(timeColumn) 

check_string_field(windowDuration, "windowDuration") 

2321 ↛ 2322line 2321 didn't jump to line 2322, because the condition on line 2321 was never true if slideDuration and startTime: 

check_string_field(slideDuration, "slideDuration") 

check_string_field(startTime, "startTime") 

res = sc._jvm.functions.window(time_col, windowDuration, slideDuration, startTime) 

2325 ↛ 2326line 2325 didn't jump to line 2326, because the condition on line 2325 was never true elif slideDuration: 

check_string_field(slideDuration, "slideDuration") 

res = sc._jvm.functions.window(time_col, windowDuration, slideDuration) 

2328 ↛ 2329line 2328 didn't jump to line 2329, because the condition on line 2328 was never true elif startTime: 

check_string_field(startTime, "startTime") 

res = sc._jvm.functions.window(time_col, windowDuration, windowDuration, startTime) 

else: 

res = sc._jvm.functions.window(time_col, windowDuration) 

return Column(res) 

 

 

def session_window(timeColumn, gapDuration): 

""" 

Generates session window given a timestamp specifying column. 

Session window is one of dynamic windows, which means the length of window is varying 

according to the given inputs. The length of session window is defined as "the timestamp 

of latest input of the session + gap duration", so when the new inputs are bound to the 

current session window, the end time of session window can be expanded according to the new 

inputs. 

Windows can support microsecond precision. Windows in the order of months are not supported. 

For a streaming query, you may use the function `current_timestamp` to generate windows on 

processing time. 

gapDuration is provided as strings, e.g. '1 second', '1 day 12 hours', '2 minutes'. Valid 

interval strings are 'week', 'day', 'hour', 'minute', 'second', 'millisecond', 'microsecond'. 

The output column will be a struct called 'session_window' by default with the nested columns 

'start' and 'end', where 'start' and 'end' will be of :class:`pyspark.sql.types.TimestampType`. 

.. versionadded:: 3.2.0 

Examples 

-------- 

>>> df = spark.createDataFrame([("2016-03-11 09:00:07", 1)]).toDF("date", "val") 

>>> w = df.groupBy(session_window("date", "5 seconds")).agg(sum("val").alias("sum")) 

>>> w.select(w.session_window.start.cast("string").alias("start"), 

... w.session_window.end.cast("string").alias("end"), "sum").collect() 

[Row(start='2016-03-11 09:00:07', end='2016-03-11 09:00:12', sum=1)] 

""" 

def check_string_field(field, fieldName): 

2361 ↛ 2362line 2361 didn't jump to line 2362, because the condition on line 2361 was never true if not field or type(field) is not str: 

raise TypeError("%s should be provided as a string" % fieldName) 

 

sc = SparkContext._active_spark_context 

time_col = _to_java_column(timeColumn) 

check_string_field(gapDuration, "gapDuration") 

res = sc._jvm.functions.session_window(time_col, gapDuration) 

return Column(res) 

 

 

# ---------------------------- misc functions ---------------------------------- 

 

def crc32(col): 

""" 

Calculates the cyclic redundancy check value (CRC32) of a binary column and 

returns the value as a bigint. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> spark.createDataFrame([('ABC',)], ['a']).select(crc32('a').alias('crc32')).collect() 

[Row(crc32=2743272264)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.crc32(_to_java_column(col))) 

 

 

def md5(col): 

"""Calculates the MD5 digest and returns the value as a 32 character hex string. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> spark.createDataFrame([('ABC',)], ['a']).select(md5('a').alias('hash')).collect() 

[Row(hash='902fbdd2b1df0c4f70b4a5d23525e932')] 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.md5(_to_java_column(col)) 

return Column(jc) 

 

 

def sha1(col): 

"""Returns the hex string result of SHA-1. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> spark.createDataFrame([('ABC',)], ['a']).select(sha1('a').alias('hash')).collect() 

[Row(hash='3c01bdbb26f358bab27f267924aa2c9a03fcfdb8')] 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.sha1(_to_java_column(col)) 

return Column(jc) 

 

 

def sha2(col, numBits): 

"""Returns the hex string result of SHA-2 family of hash functions (SHA-224, SHA-256, SHA-384, 

and SHA-512). The numBits indicates the desired bit length of the result, which must have a 

value of 224, 256, 384, 512, or 0 (which is equivalent to 256). 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> digests = df.select(sha2(df.name, 256).alias('s')).collect() 

>>> digests[0] 

Row(s='3bc51062973c458d5a6f2d8d64a023246354ad7e064b1e4e009ec8a0699a3043') 

>>> digests[1] 

Row(s='cd9fb1e148ccd8442e5aa74904cc73bf6fb54d1d54d333bd596aa9bb4bb4e961') 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.sha2(_to_java_column(col), numBits) 

return Column(jc) 

 

 

def hash(*cols): 

"""Calculates the hash code of given columns, and returns the result as an int column. 

 

.. versionadded:: 2.0.0 

 

Examples 

-------- 

>>> spark.createDataFrame([('ABC',)], ['a']).select(hash('a').alias('hash')).collect() 

[Row(hash=-757602832)] 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.hash(_to_seq(sc, cols, _to_java_column)) 

return Column(jc) 

 

 

def xxhash64(*cols): 

"""Calculates the hash code of given columns using the 64-bit variant of the xxHash algorithm, 

and returns the result as a long column. 

 

.. versionadded:: 3.0.0 

 

Examples 

-------- 

>>> spark.createDataFrame([('ABC',)], ['a']).select(xxhash64('a').alias('hash')).collect() 

[Row(hash=4105715581806190027)] 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.xxhash64(_to_seq(sc, cols, _to_java_column)) 

return Column(jc) 

 

 

def assert_true(col, errMsg=None): 

""" 

Returns null if the input column is true; throws an exception with the provided error message 

otherwise. 

 

.. versionadded:: 3.1.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(0,1)], ['a', 'b']) 

>>> df.select(assert_true(df.a < df.b).alias('r')).collect() 

[Row(r=None)] 

>>> df = spark.createDataFrame([(0,1)], ['a', 'b']) 

>>> df.select(assert_true(df.a < df.b, df.a).alias('r')).collect() 

[Row(r=None)] 

>>> df = spark.createDataFrame([(0,1)], ['a', 'b']) 

>>> df.select(assert_true(df.a < df.b, 'error').alias('r')).collect() 

[Row(r=None)] 

""" 

sc = SparkContext._active_spark_context 

if errMsg is None: 

return Column(sc._jvm.functions.assert_true(_to_java_column(col))) 

if not isinstance(errMsg, (str, Column)): 

raise TypeError( 

"errMsg should be a Column or a str, got {}".format(type(errMsg)) 

) 

 

errMsg = ( 

_create_column_from_literal(errMsg) 

if isinstance(errMsg, str) 

else _to_java_column(errMsg) 

) 

return Column(sc._jvm.functions.assert_true(_to_java_column(col), errMsg)) 

 

 

@since(3.1) 

def raise_error(errMsg): 

""" 

Throws an exception with the provided error message. 

""" 

if not isinstance(errMsg, (str, Column)): 

raise TypeError( 

"errMsg should be a Column or a str, got {}".format(type(errMsg)) 

) 

 

sc = SparkContext._active_spark_context 

errMsg = ( 

_create_column_from_literal(errMsg) 

if isinstance(errMsg, str) 

else _to_java_column(errMsg) 

) 

return Column(sc._jvm.functions.raise_error(errMsg)) 

 

 

# ---------------------- String/Binary functions ------------------------------ 

 

@since(1.5) 

def upper(col): 

""" 

Converts a string expression to upper case. 

""" 

return _invoke_function_over_column("upper", col) 

 

 

@since(1.5) 

def lower(col): 

""" 

Converts a string expression to lower case. 

""" 

return _invoke_function_over_column("lower", col) 

 

 

@since(1.5) 

def ascii(col): 

""" 

Computes the numeric value of the first character of the string column. 

""" 

return _invoke_function_over_column("ascii", col) 

 

 

@since(1.5) 

def base64(col): 

""" 

Computes the BASE64 encoding of a binary column and returns it as a string column. 

""" 

return _invoke_function_over_column("base64", col) 

 

 

@since(1.5) 

def unbase64(col): 

""" 

Decodes a BASE64 encoded string column and returns it as a binary column. 

""" 

return _invoke_function_over_column("unbase64", col) 

 

 

@since(1.5) 

def ltrim(col): 

""" 

Trim the spaces from left end for the specified string value. 

""" 

return _invoke_function_over_column("ltrim", col) 

 

 

@since(1.5) 

def rtrim(col): 

""" 

Trim the spaces from right end for the specified string value. 

""" 

return _invoke_function_over_column("rtrim", col) 

 

 

@since(1.5) 

def trim(col): 

""" 

Trim the spaces from both ends for the specified string column. 

""" 

return _invoke_function_over_column("trim", col) 

 

 

def concat_ws(sep, *cols): 

""" 

Concatenates multiple input string columns together into a single string column, 

using the given separator. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('abcd','123')], ['s', 'd']) 

>>> df.select(concat_ws('-', df.s, df.d).alias('s')).collect() 

[Row(s='abcd-123')] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.concat_ws(sep, _to_seq(sc, cols, _to_java_column))) 

 

 

@since(1.5) 

def decode(col, charset): 

""" 

Computes the first argument into a string from a binary using the provided character set 

(one of 'US-ASCII', 'ISO-8859-1', 'UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16'). 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.decode(_to_java_column(col), charset)) 

 

 

@since(1.5) 

def encode(col, charset): 

""" 

Computes the first argument into a binary from a string using the provided character set 

(one of 'US-ASCII', 'ISO-8859-1', 'UTF-8', 'UTF-16BE', 'UTF-16LE', 'UTF-16'). 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.encode(_to_java_column(col), charset)) 

 

 

def format_number(col, d): 

""" 

Formats the number X to a format like '#,--#,--#.--', rounded to d decimal places 

with HALF_EVEN round mode, and returns the result as a string. 

 

.. versionadded:: 1.5.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

the column name of the numeric value to be formatted 

d : int 

the N decimal places 

 

>>> spark.createDataFrame([(5,)], ['a']).select(format_number('a', 4).alias('v')).collect() 

[Row(v='5.0000')] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.format_number(_to_java_column(col), d)) 

 

 

def format_string(format, *cols): 

""" 

Formats the arguments in printf-style and returns the result as a string column. 

 

.. versionadded:: 1.5.0 

 

Parameters 

---------- 

format : str 

string that can contain embedded format tags and used as result column's value 

cols : :class:`~pyspark.sql.Column` or str 

column names or :class:`~pyspark.sql.Column`\\s to be used in formatting 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(5, "hello")], ['a', 'b']) 

>>> df.select(format_string('%d %s', df.a, df.b).alias('v')).collect() 

[Row(v='5 hello')] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.format_string(format, _to_seq(sc, cols, _to_java_column))) 

 

 

def instr(str, substr): 

""" 

Locate the position of the first occurrence of substr column in the given string. 

Returns null if either of the arguments are null. 

 

.. versionadded:: 1.5.0 

 

Notes 

----- 

The position is not zero based, but 1 based index. Returns 0 if substr 

could not be found in str. 

 

>>> df = spark.createDataFrame([('abcd',)], ['s',]) 

>>> df.select(instr(df.s, 'b').alias('s')).collect() 

[Row(s=2)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.instr(_to_java_column(str), substr)) 

 

 

def overlay(src, replace, pos, len=-1): 

""" 

Overlay the specified portion of `src` with `replace`, 

starting from byte position `pos` of `src` and proceeding for `len` bytes. 

 

.. versionadded:: 3.0.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([("SPARK_SQL", "CORE")], ("x", "y")) 

>>> df.select(overlay("x", "y", 7).alias("overlayed")).show() 

+----------+ 

| overlayed| 

+----------+ 

|SPARK_CORE| 

+----------+ 

""" 

2708 ↛ 2709line 2708 didn't jump to line 2709, because the condition on line 2708 was never true if not isinstance(pos, (int, str, Column)): 

raise TypeError( 

"pos should be an integer or a Column / column name, got {}".format(type(pos))) 

2711 ↛ 2712line 2711 didn't jump to line 2712, because the condition on line 2711 was never true if len is not None and not isinstance(len, (int, str, Column)): 

raise TypeError( 

"len should be an integer or a Column / column name, got {}".format(type(len))) 

 

pos = _create_column_from_literal(pos) if isinstance(pos, int) else _to_java_column(pos) 

len = _create_column_from_literal(len) if isinstance(len, int) else _to_java_column(len) 

 

sc = SparkContext._active_spark_context 

 

return Column(sc._jvm.functions.overlay( 

_to_java_column(src), 

_to_java_column(replace), 

pos, 

len 

)) 

 

 

def sentences(string, language=None, country=None): 

""" 

Splits a string into arrays of sentences, where each sentence is an array of words. 

The 'language' and 'country' arguments are optional, and if omitted, the default locale is used. 

 

.. versionadded:: 3.2.0 

 

Parameters 

---------- 

string : :class:`~pyspark.sql.Column` or str 

a string to be split 

language : :class:`~pyspark.sql.Column` or str, optional 

a language of the locale 

country : :class:`~pyspark.sql.Column` or str, optional 

a country of the locale 

 

Examples 

-------- 

>>> df = spark.createDataFrame([["This is an example sentence."]], ["string"]) 

>>> df.select(sentences(df.string, lit("en"), lit("US"))).show(truncate=False) 

+-----------------------------------+ 

|sentences(string, en, US) | 

+-----------------------------------+ 

|[[This, is, an, example, sentence]]| 

+-----------------------------------+ 

""" 

2754 ↛ 2755line 2754 didn't jump to line 2755, because the condition on line 2754 was never true if language is None: 

language = lit("") 

2756 ↛ 2757line 2756 didn't jump to line 2757, because the condition on line 2756 was never true if country is None: 

country = lit("") 

 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.sentences( 

_to_java_column(string), 

_to_java_column(language), 

_to_java_column(country) 

)) 

 

 

def substring(str, pos, len): 

""" 

Substring starts at `pos` and is of length `len` when str is String type or 

returns the slice of byte array that starts at `pos` in byte and is of length `len` 

when str is Binary type. 

 

.. versionadded:: 1.5.0 

 

Notes 

----- 

The position is not zero based, but 1 based index. 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('abcd',)], ['s',]) 

>>> df.select(substring(df.s, 1, 2).alias('s')).collect() 

[Row(s='ab')] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.substring(_to_java_column(str), pos, len)) 

 

 

def substring_index(str, delim, count): 

""" 

Returns the substring from string str before count occurrences of the delimiter delim. 

If count is positive, everything the left of the final delimiter (counting from left) is 

returned. If count is negative, every to the right of the final delimiter (counting from the 

right) is returned. substring_index performs a case-sensitive match when searching for delim. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('a.b.c.d',)], ['s']) 

>>> df.select(substring_index(df.s, '.', 2).alias('s')).collect() 

[Row(s='a.b')] 

>>> df.select(substring_index(df.s, '.', -3).alias('s')).collect() 

[Row(s='b.c.d')] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.substring_index(_to_java_column(str), delim, count)) 

 

 

def levenshtein(left, right): 

"""Computes the Levenshtein distance of the two given strings. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df0 = spark.createDataFrame([('kitten', 'sitting',)], ['l', 'r']) 

>>> df0.select(levenshtein('l', 'r').alias('d')).collect() 

[Row(d=3)] 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.levenshtein(_to_java_column(left), _to_java_column(right)) 

return Column(jc) 

 

 

def locate(substr, str, pos=1): 

""" 

Locate the position of the first occurrence of substr in a string column, after position pos. 

 

.. versionadded:: 1.5.0 

 

Parameters 

---------- 

substr : str 

a string 

str : :class:`~pyspark.sql.Column` or str 

a Column of :class:`pyspark.sql.types.StringType` 

pos : int, optional 

start position (zero based) 

 

Notes 

----- 

The position is not zero based, but 1 based index. Returns 0 if substr 

could not be found in str. 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('abcd',)], ['s',]) 

>>> df.select(locate('b', df.s, 1).alias('s')).collect() 

[Row(s=2)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.locate(substr, _to_java_column(str), pos)) 

 

 

def lpad(col, len, pad): 

""" 

Left-pad the string column to width `len` with `pad`. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('abcd',)], ['s',]) 

>>> df.select(lpad(df.s, 6, '#').alias('s')).collect() 

[Row(s='##abcd')] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.lpad(_to_java_column(col), len, pad)) 

 

 

def rpad(col, len, pad): 

""" 

Right-pad the string column to width `len` with `pad`. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('abcd',)], ['s',]) 

>>> df.select(rpad(df.s, 6, '#').alias('s')).collect() 

[Row(s='abcd##')] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.rpad(_to_java_column(col), len, pad)) 

 

 

def repeat(col, n): 

""" 

Repeats a string column n times, and returns it as a new string column. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('ab',)], ['s',]) 

>>> df.select(repeat(df.s, 3).alias('s')).collect() 

[Row(s='ababab')] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.repeat(_to_java_column(col), n)) 

 

 

def split(str, pattern, limit=-1): 

""" 

Splits str around matches of the given pattern. 

 

.. versionadded:: 1.5.0 

 

Parameters 

---------- 

str : :class:`~pyspark.sql.Column` or str 

a string expression to split 

pattern : str 

a string representing a regular expression. The regex string should be 

a Java regular expression. 

limit : int, optional 

an integer which controls the number of times `pattern` is applied. 

 

* ``limit > 0``: The resulting array's length will not be more than `limit`, and the 

resulting array's last entry will contain all input beyond the last 

matched pattern. 

* ``limit <= 0``: `pattern` will be applied as many times as possible, and the resulting 

array can be of any size. 

 

.. versionchanged:: 3.0 

`split` now takes an optional `limit` field. If not provided, default limit value is -1. 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('oneAtwoBthreeC',)], ['s',]) 

>>> df.select(split(df.s, '[ABC]', 2).alias('s')).collect() 

[Row(s=['one', 'twoBthreeC'])] 

>>> df.select(split(df.s, '[ABC]', -1).alias('s')).collect() 

[Row(s=['one', 'two', 'three', ''])] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.split(_to_java_column(str), pattern, limit)) 

 

 

def regexp_extract(str, pattern, idx): 

r"""Extract a specific group matched by a Java regex, from the specified string column. 

If the regex did not match, or the specified group did not match, an empty string is returned. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('100-200',)], ['str']) 

>>> df.select(regexp_extract('str', r'(\d+)-(\d+)', 1).alias('d')).collect() 

[Row(d='100')] 

>>> df = spark.createDataFrame([('foo',)], ['str']) 

>>> df.select(regexp_extract('str', r'(\d+)', 1).alias('d')).collect() 

[Row(d='')] 

>>> df = spark.createDataFrame([('aaaac',)], ['str']) 

>>> df.select(regexp_extract('str', '(a+)(b)?(c)', 2).alias('d')).collect() 

[Row(d='')] 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.regexp_extract(_to_java_column(str), pattern, idx) 

return Column(jc) 

 

 

def regexp_replace(str, pattern, replacement): 

r"""Replace all substrings of the specified string value that match regexp with rep. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('100-200',)], ['str']) 

>>> df.select(regexp_replace('str', r'(\d+)', '--').alias('d')).collect() 

[Row(d='-----')] 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.regexp_replace(_to_java_column(str), pattern, replacement) 

return Column(jc) 

 

 

def initcap(col): 

"""Translate the first letter of each word to upper case in the sentence. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> spark.createDataFrame([('ab cd',)], ['a']).select(initcap("a").alias('v')).collect() 

[Row(v='Ab Cd')] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.initcap(_to_java_column(col))) 

 

 

def soundex(col): 

""" 

Returns the SoundEx encoding for a string 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([("Peters",),("Uhrbach",)], ['name']) 

>>> df.select(soundex(df.name).alias("soundex")).collect() 

[Row(soundex='P362'), Row(soundex='U612')] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.soundex(_to_java_column(col))) 

 

 

def bin(col): 

"""Returns the string representation of the binary value of the given column. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df.select(bin(df.age).alias('c')).collect() 

[Row(c='10'), Row(c='101')] 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.bin(_to_java_column(col)) 

return Column(jc) 

 

 

def hex(col): 

"""Computes hex value of the given column, which could be :class:`pyspark.sql.types.StringType`, 

:class:`pyspark.sql.types.BinaryType`, :class:`pyspark.sql.types.IntegerType` or 

:class:`pyspark.sql.types.LongType`. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> spark.createDataFrame([('ABC', 3)], ['a', 'b']).select(hex('a'), hex('b')).collect() 

[Row(hex(a)='414243', hex(b)='3')] 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.hex(_to_java_column(col)) 

return Column(jc) 

 

 

def unhex(col): 

"""Inverse of hex. Interprets each pair of characters as a hexadecimal number 

and converts to the byte representation of number. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> spark.createDataFrame([('414243',)], ['a']).select(unhex('a')).collect() 

[Row(unhex(a)=bytearray(b'ABC'))] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.unhex(_to_java_column(col))) 

 

 

def length(col): 

"""Computes the character length of string data or number of bytes of binary data. 

The length of character data includes the trailing spaces. The length of binary data 

includes binary zeros. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> spark.createDataFrame([('ABC ',)], ['a']).select(length('a').alias('length')).collect() 

[Row(length=4)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.length(_to_java_column(col))) 

 

 

def translate(srcCol, matching, replace): 

"""A function translate any character in the `srcCol` by a character in `matching`. 

The characters in `replace` is corresponding to the characters in `matching`. 

The translate will happen when any character in the string matching with the character 

in the `matching`. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> spark.createDataFrame([('translate',)], ['a']).select(translate('a', "rnlt", "123") \\ 

... .alias('r')).collect() 

[Row(r='1a2s3ae')] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.translate(_to_java_column(srcCol), matching, replace)) 

 

 

# ---------------------- Collection functions ------------------------------ 

 

def create_map(*cols): 

"""Creates a new map column. 

 

.. versionadded:: 2.0.0 

 

Parameters 

---------- 

cols : :class:`~pyspark.sql.Column` or str 

column names or :class:`~pyspark.sql.Column`\\s that are 

grouped as key-value pairs, e.g. (key1, value1, key2, value2, ...). 

 

Examples 

-------- 

>>> df.select(create_map('name', 'age').alias("map")).collect() 

[Row(map={'Alice': 2}), Row(map={'Bob': 5})] 

>>> df.select(create_map([df.name, df.age]).alias("map")).collect() 

[Row(map={'Alice': 2}), Row(map={'Bob': 5})] 

""" 

sc = SparkContext._active_spark_context 

if len(cols) == 1 and isinstance(cols[0], (list, set)): 

cols = cols[0] 

jc = sc._jvm.functions.map(_to_seq(sc, cols, _to_java_column)) 

return Column(jc) 

 

 

def map_from_arrays(col1, col2): 

"""Creates a new map from two arrays. 

 

.. versionadded:: 2.4.0 

 

Parameters 

---------- 

col1 : :class:`~pyspark.sql.Column` or str 

name of column containing a set of keys. All elements should not be null 

col2 : :class:`~pyspark.sql.Column` or str 

name of column containing a set of values 

 

Examples 

-------- 

>>> df = spark.createDataFrame([([2, 5], ['a', 'b'])], ['k', 'v']) 

>>> df.select(map_from_arrays(df.k, df.v).alias("map")).show() 

+----------------+ 

| map| 

+----------------+ 

|{2 -> a, 5 -> b}| 

+----------------+ 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.map_from_arrays(_to_java_column(col1), _to_java_column(col2))) 

 

 

def array(*cols): 

"""Creates a new array column. 

 

.. versionadded:: 1.4.0 

 

Parameters 

---------- 

cols : :class:`~pyspark.sql.Column` or str 

column names or :class:`~pyspark.sql.Column`\\s that have 

the same data type. 

 

Examples 

-------- 

>>> df.select(array('age', 'age').alias("arr")).collect() 

[Row(arr=[2, 2]), Row(arr=[5, 5])] 

>>> df.select(array([df.age, df.age]).alias("arr")).collect() 

[Row(arr=[2, 2]), Row(arr=[5, 5])] 

""" 

sc = SparkContext._active_spark_context 

if len(cols) == 1 and isinstance(cols[0], (list, set)): 

cols = cols[0] 

jc = sc._jvm.functions.array(_to_seq(sc, cols, _to_java_column)) 

return Column(jc) 

 

 

def array_contains(col, value): 

""" 

Collection function: returns null if the array is null, true if the array contains the 

given value, and false otherwise. 

 

.. versionadded:: 1.5.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column containing array 

value : 

value or column to check for in array 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(["a", "b", "c"],), ([],)], ['data']) 

>>> df.select(array_contains(df.data, "a")).collect() 

[Row(array_contains(data, a)=True), Row(array_contains(data, a)=False)] 

>>> df.select(array_contains(df.data, lit("a"))).collect() 

[Row(array_contains(data, a)=True), Row(array_contains(data, a)=False)] 

""" 

sc = SparkContext._active_spark_context 

value = value._jc if isinstance(value, Column) else value 

return Column(sc._jvm.functions.array_contains(_to_java_column(col), value)) 

 

 

def arrays_overlap(a1, a2): 

""" 

Collection function: returns true if the arrays contain any common non-null element; if not, 

returns null if both the arrays are non-empty and any of them contains a null element; returns 

false otherwise. 

 

.. versionadded:: 2.4.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(["a", "b"], ["b", "c"]), (["a"], ["b", "c"])], ['x', 'y']) 

>>> df.select(arrays_overlap(df.x, df.y).alias("overlap")).collect() 

[Row(overlap=True), Row(overlap=False)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.arrays_overlap(_to_java_column(a1), _to_java_column(a2))) 

 

 

def slice(x, start, length): 

""" 

Collection function: returns an array containing all the elements in `x` from index `start` 

(array indices start at 1, or from the end if `start` is negative) with the specified `length`. 

 

.. versionadded:: 2.4.0 

 

Parameters 

---------- 

x : :class:`~pyspark.sql.Column` or str 

the array to be sliced 

start : :class:`~pyspark.sql.Column` or int 

the starting index 

length : :class:`~pyspark.sql.Column` or int 

the length of the slice 

 

Examples 

-------- 

>>> df = spark.createDataFrame([([1, 2, 3],), ([4, 5],)], ['x']) 

>>> df.select(slice(df.x, 2, 2).alias("sliced")).collect() 

[Row(sliced=[2, 3]), Row(sliced=[5])] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.slice( 

_to_java_column(x), 

start._jc if isinstance(start, Column) else start, 

length._jc if isinstance(length, Column) else length 

)) 

 

 

def array_join(col, delimiter, null_replacement=None): 

""" 

Concatenates the elements of `column` using the `delimiter`. Null values are replaced with 

`null_replacement` if set, otherwise they are ignored. 

 

.. versionadded:: 2.4.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(["a", "b", "c"],), (["a", None],)], ['data']) 

>>> df.select(array_join(df.data, ",").alias("joined")).collect() 

[Row(joined='a,b,c'), Row(joined='a')] 

>>> df.select(array_join(df.data, ",", "NULL").alias("joined")).collect() 

[Row(joined='a,b,c'), Row(joined='a,NULL')] 

""" 

sc = SparkContext._active_spark_context 

if null_replacement is None: 

return Column(sc._jvm.functions.array_join(_to_java_column(col), delimiter)) 

else: 

return Column(sc._jvm.functions.array_join( 

_to_java_column(col), delimiter, null_replacement)) 

 

 

def concat(*cols): 

""" 

Concatenates multiple input columns together into a single column. 

The function works with strings, binary and compatible array columns. 

 

.. versionadded:: 1.5.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('abcd','123')], ['s', 'd']) 

>>> df.select(concat(df.s, df.d).alias('s')).collect() 

[Row(s='abcd123')] 

 

>>> df = spark.createDataFrame([([1, 2], [3, 4], [5]), ([1, 2], None, [3])], ['a', 'b', 'c']) 

>>> df.select(concat(df.a, df.b, df.c).alias("arr")).collect() 

[Row(arr=[1, 2, 3, 4, 5]), Row(arr=None)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.concat(_to_seq(sc, cols, _to_java_column))) 

 

 

def array_position(col, value): 

""" 

Collection function: Locates the position of the first occurrence of the given value 

in the given array. Returns null if either of the arguments are null. 

 

.. versionadded:: 2.4.0 

 

Notes 

----- 

The position is not zero based, but 1 based index. Returns 0 if the given 

value could not be found in the array. 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(["c", "b", "a"],), ([],)], ['data']) 

>>> df.select(array_position(df.data, "a")).collect() 

[Row(array_position(data, a)=3), Row(array_position(data, a)=0)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.array_position(_to_java_column(col), value)) 

 

 

def element_at(col, extraction): 

""" 

Collection function: Returns element of array at given index in extraction if col is array. 

Returns value for the given key in extraction if col is map. 

 

.. versionadded:: 2.4.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column containing array or map 

extraction : 

index to check for in array or key to check for in map 

 

Notes 

----- 

The position is not zero based, but 1 based index. 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(["a", "b", "c"],), ([],)], ['data']) 

>>> df.select(element_at(df.data, 1)).collect() 

[Row(element_at(data, 1)='a'), Row(element_at(data, 1)=None)] 

 

>>> df = spark.createDataFrame([({"a": 1.0, "b": 2.0},), ({},)], ['data']) 

>>> df.select(element_at(df.data, lit("a"))).collect() 

[Row(element_at(data, a)=1.0), Row(element_at(data, a)=None)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.element_at( 

_to_java_column(col), lit(extraction)._jc)) 

 

 

def array_remove(col, element): 

""" 

Collection function: Remove all elements that equal to element from the given array. 

 

.. versionadded:: 2.4.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column containing array 

element : 

element to be removed from the array 

 

Examples 

-------- 

>>> df = spark.createDataFrame([([1, 2, 3, 1, 1],), ([],)], ['data']) 

>>> df.select(array_remove(df.data, 1)).collect() 

[Row(array_remove(data, 1)=[2, 3]), Row(array_remove(data, 1)=[])] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.array_remove(_to_java_column(col), element)) 

 

 

def array_distinct(col): 

""" 

Collection function: removes duplicate values from the array. 

 

.. versionadded:: 2.4.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

 

Examples 

-------- 

>>> df = spark.createDataFrame([([1, 2, 3, 2],), ([4, 5, 5, 4],)], ['data']) 

>>> df.select(array_distinct(df.data)).collect() 

[Row(array_distinct(data)=[1, 2, 3]), Row(array_distinct(data)=[4, 5])] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.array_distinct(_to_java_column(col))) 

 

 

def array_intersect(col1, col2): 

""" 

Collection function: returns an array of the elements in the intersection of col1 and col2, 

without duplicates. 

 

.. versionadded:: 2.4.0 

 

Parameters 

---------- 

col1 : :class:`~pyspark.sql.Column` or str 

name of column containing array 

col2 : :class:`~pyspark.sql.Column` or str 

name of column containing array 

 

Examples 

-------- 

>>> from pyspark.sql import Row 

>>> df = spark.createDataFrame([Row(c1=["b", "a", "c"], c2=["c", "d", "a", "f"])]) 

>>> df.select(array_intersect(df.c1, df.c2)).collect() 

[Row(array_intersect(c1, c2)=['a', 'c'])] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.array_intersect(_to_java_column(col1), _to_java_column(col2))) 

 

 

def array_union(col1, col2): 

""" 

Collection function: returns an array of the elements in the union of col1 and col2, 

without duplicates. 

 

.. versionadded:: 2.4.0 

 

Parameters 

---------- 

col1 : :class:`~pyspark.sql.Column` or str 

name of column containing array 

col2 : :class:`~pyspark.sql.Column` or str 

name of column containing array 

 

Examples 

-------- 

>>> from pyspark.sql import Row 

>>> df = spark.createDataFrame([Row(c1=["b", "a", "c"], c2=["c", "d", "a", "f"])]) 

>>> df.select(array_union(df.c1, df.c2)).collect() 

[Row(array_union(c1, c2)=['b', 'a', 'c', 'd', 'f'])] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.array_union(_to_java_column(col1), _to_java_column(col2))) 

 

 

def array_except(col1, col2): 

""" 

Collection function: returns an array of the elements in col1 but not in col2, 

without duplicates. 

 

.. versionadded:: 2.4.0 

 

Parameters 

---------- 

col1 : :class:`~pyspark.sql.Column` or str 

name of column containing array 

col2 : :class:`~pyspark.sql.Column` or str 

name of column containing array 

 

Examples 

-------- 

>>> from pyspark.sql import Row 

>>> df = spark.createDataFrame([Row(c1=["b", "a", "c"], c2=["c", "d", "a", "f"])]) 

>>> df.select(array_except(df.c1, df.c2)).collect() 

[Row(array_except(c1, c2)=['b'])] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.array_except(_to_java_column(col1), _to_java_column(col2))) 

 

 

def explode(col): 

""" 

Returns a new row for each element in the given array or map. 

Uses the default column name `col` for elements in the array and 

`key` and `value` for elements in the map unless specified otherwise. 

 

.. versionadded:: 1.4.0 

 

Examples 

-------- 

>>> from pyspark.sql import Row 

>>> eDF = spark.createDataFrame([Row(a=1, intlist=[1,2,3], mapfield={"a": "b"})]) 

>>> eDF.select(explode(eDF.intlist).alias("anInt")).collect() 

[Row(anInt=1), Row(anInt=2), Row(anInt=3)] 

 

>>> eDF.select(explode(eDF.mapfield).alias("key", "value")).show() 

+---+-----+ 

|key|value| 

+---+-----+ 

| a| b| 

+---+-----+ 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.explode(_to_java_column(col)) 

return Column(jc) 

 

 

def posexplode(col): 

""" 

Returns a new row for each element with position in the given array or map. 

Uses the default column name `pos` for position, and `col` for elements in the 

array and `key` and `value` for elements in the map unless specified otherwise. 

 

.. versionadded:: 2.1.0 

 

Examples 

-------- 

>>> from pyspark.sql import Row 

>>> eDF = spark.createDataFrame([Row(a=1, intlist=[1,2,3], mapfield={"a": "b"})]) 

>>> eDF.select(posexplode(eDF.intlist)).collect() 

[Row(pos=0, col=1), Row(pos=1, col=2), Row(pos=2, col=3)] 

 

>>> eDF.select(posexplode(eDF.mapfield)).show() 

+---+---+-----+ 

|pos|key|value| 

+---+---+-----+ 

| 0| a| b| 

+---+---+-----+ 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.posexplode(_to_java_column(col)) 

return Column(jc) 

 

 

def explode_outer(col): 

""" 

Returns a new row for each element in the given array or map. 

Unlike explode, if the array/map is null or empty then null is produced. 

Uses the default column name `col` for elements in the array and 

`key` and `value` for elements in the map unless specified otherwise. 

 

.. versionadded:: 2.3.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame( 

... [(1, ["foo", "bar"], {"x": 1.0}), (2, [], {}), (3, None, None)], 

... ("id", "an_array", "a_map") 

... ) 

>>> df.select("id", "an_array", explode_outer("a_map")).show() 

+---+----------+----+-----+ 

| id| an_array| key|value| 

+---+----------+----+-----+ 

| 1|[foo, bar]| x| 1.0| 

| 2| []|null| null| 

| 3| null|null| null| 

+---+----------+----+-----+ 

 

>>> df.select("id", "a_map", explode_outer("an_array")).show() 

+---+----------+----+ 

| id| a_map| col| 

+---+----------+----+ 

| 1|{x -> 1.0}| foo| 

| 1|{x -> 1.0}| bar| 

| 2| {}|null| 

| 3| null|null| 

+---+----------+----+ 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.explode_outer(_to_java_column(col)) 

return Column(jc) 

 

 

def posexplode_outer(col): 

""" 

Returns a new row for each element with position in the given array or map. 

Unlike posexplode, if the array/map is null or empty then the row (null, null) is produced. 

Uses the default column name `pos` for position, and `col` for elements in the 

array and `key` and `value` for elements in the map unless specified otherwise. 

 

.. versionadded:: 2.3.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame( 

... [(1, ["foo", "bar"], {"x": 1.0}), (2, [], {}), (3, None, None)], 

... ("id", "an_array", "a_map") 

... ) 

>>> df.select("id", "an_array", posexplode_outer("a_map")).show() 

+---+----------+----+----+-----+ 

| id| an_array| pos| key|value| 

+---+----------+----+----+-----+ 

| 1|[foo, bar]| 0| x| 1.0| 

| 2| []|null|null| null| 

| 3| null|null|null| null| 

+---+----------+----+----+-----+ 

>>> df.select("id", "a_map", posexplode_outer("an_array")).show() 

+---+----------+----+----+ 

| id| a_map| pos| col| 

+---+----------+----+----+ 

| 1|{x -> 1.0}| 0| foo| 

| 1|{x -> 1.0}| 1| bar| 

| 2| {}|null|null| 

| 3| null|null|null| 

+---+----------+----+----+ 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.posexplode_outer(_to_java_column(col)) 

return Column(jc) 

 

 

def get_json_object(col, path): 

""" 

Extracts json object from a json string based on json path specified, and returns json string 

of the extracted json object. It will return null if the input json string is invalid. 

 

.. versionadded:: 1.6.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

string column in json format 

path : str 

path to the json object to extract 

 

Examples 

-------- 

>>> data = [("1", '''{"f1": "value1", "f2": "value2"}'''), ("2", '''{"f1": "value12"}''')] 

>>> df = spark.createDataFrame(data, ("key", "jstring")) 

>>> df.select(df.key, get_json_object(df.jstring, '$.f1').alias("c0"), \\ 

... get_json_object(df.jstring, '$.f2').alias("c1") ).collect() 

[Row(key='1', c0='value1', c1='value2'), Row(key='2', c0='value12', c1=None)] 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.get_json_object(_to_java_column(col), path) 

return Column(jc) 

 

 

def json_tuple(col, *fields): 

"""Creates a new row for a json column according to the given field names. 

 

.. versionadded:: 1.6.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

string column in json format 

fields : str 

fields to extract 

 

Examples 

-------- 

>>> data = [("1", '''{"f1": "value1", "f2": "value2"}'''), ("2", '''{"f1": "value12"}''')] 

>>> df = spark.createDataFrame(data, ("key", "jstring")) 

>>> df.select(df.key, json_tuple(df.jstring, 'f1', 'f2')).collect() 

[Row(key='1', c0='value1', c1='value2'), Row(key='2', c0='value12', c1=None)] 

""" 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.json_tuple(_to_java_column(col), _to_seq(sc, fields)) 

return Column(jc) 

 

 

def from_json(col, schema, options=None): 

""" 

Parses a column containing a JSON string into a :class:`MapType` with :class:`StringType` 

as keys type, :class:`StructType` or :class:`ArrayType` with 

the specified schema. Returns `null`, in the case of an unparseable string. 

 

.. versionadded:: 2.1.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

string column in json format 

schema : :class:`DataType` or str 

a StructType or ArrayType of StructType to use when parsing the json column. 

 

.. versionchanged:: 2.3 

the DDL-formatted string is also supported for ``schema``. 

options : dict, optional 

options to control parsing. accepts the same options as the json datasource. 

See `Data Source Option <https://spark.apache.org/docs/latest/sql-data-sources-json.html#data-source-option>`_ 

in the version you use. 

 

.. # noqa 

 

Examples 

-------- 

>>> from pyspark.sql.types import * 

>>> data = [(1, '''{"a": 1}''')] 

>>> schema = StructType([StructField("a", IntegerType())]) 

>>> df = spark.createDataFrame(data, ("key", "value")) 

>>> df.select(from_json(df.value, schema).alias("json")).collect() 

[Row(json=Row(a=1))] 

>>> df.select(from_json(df.value, "a INT").alias("json")).collect() 

[Row(json=Row(a=1))] 

>>> df.select(from_json(df.value, "MAP<STRING,INT>").alias("json")).collect() 

[Row(json={'a': 1})] 

>>> data = [(1, '''[{"a": 1}]''')] 

>>> schema = ArrayType(StructType([StructField("a", IntegerType())])) 

>>> df = spark.createDataFrame(data, ("key", "value")) 

>>> df.select(from_json(df.value, schema).alias("json")).collect() 

[Row(json=[Row(a=1)])] 

>>> schema = schema_of_json(lit('''{"a": 0}''')) 

>>> df.select(from_json(df.value, schema).alias("json")).collect() 

[Row(json=Row(a=None))] 

>>> data = [(1, '''[1, 2, 3]''')] 

>>> schema = ArrayType(IntegerType()) 

>>> df = spark.createDataFrame(data, ("key", "value")) 

>>> df.select(from_json(df.value, schema).alias("json")).collect() 

[Row(json=[1, 2, 3])] 

""" 

 

sc = SparkContext._active_spark_context 

if isinstance(schema, DataType): 

schema = schema.json() 

elif isinstance(schema, Column): 

schema = _to_java_column(schema) 

jc = sc._jvm.functions.from_json(_to_java_column(col), schema, _options_to_str(options)) 

return Column(jc) 

 

 

def to_json(col, options=None): 

""" 

Converts a column containing a :class:`StructType`, :class:`ArrayType` or a :class:`MapType` 

into a JSON string. Throws an exception, in the case of an unsupported type. 

 

.. versionadded:: 2.1.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column containing a struct, an array or a map. 

options : dict, optional 

options to control converting. accepts the same options as the JSON datasource. 

See `Data Source Option <https://spark.apache.org/docs/latest/sql-data-sources-json.html#data-source-option>`_ 

in the version you use. 

Additionally the function supports the `pretty` option which enables 

pretty JSON generation. 

 

.. # noqa 

 

Examples 

-------- 

>>> from pyspark.sql import Row 

>>> from pyspark.sql.types import * 

>>> data = [(1, Row(age=2, name='Alice'))] 

>>> df = spark.createDataFrame(data, ("key", "value")) 

>>> df.select(to_json(df.value).alias("json")).collect() 

[Row(json='{"age":2,"name":"Alice"}')] 

>>> data = [(1, [Row(age=2, name='Alice'), Row(age=3, name='Bob')])] 

>>> df = spark.createDataFrame(data, ("key", "value")) 

>>> df.select(to_json(df.value).alias("json")).collect() 

[Row(json='[{"age":2,"name":"Alice"},{"age":3,"name":"Bob"}]')] 

>>> data = [(1, {"name": "Alice"})] 

>>> df = spark.createDataFrame(data, ("key", "value")) 

>>> df.select(to_json(df.value).alias("json")).collect() 

[Row(json='{"name":"Alice"}')] 

>>> data = [(1, [{"name": "Alice"}, {"name": "Bob"}])] 

>>> df = spark.createDataFrame(data, ("key", "value")) 

>>> df.select(to_json(df.value).alias("json")).collect() 

[Row(json='[{"name":"Alice"},{"name":"Bob"}]')] 

>>> data = [(1, ["Alice", "Bob"])] 

>>> df = spark.createDataFrame(data, ("key", "value")) 

>>> df.select(to_json(df.value).alias("json")).collect() 

[Row(json='["Alice","Bob"]')] 

""" 

 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.to_json(_to_java_column(col), _options_to_str(options)) 

return Column(jc) 

 

 

def schema_of_json(json, options=None): 

""" 

Parses a JSON string and infers its schema in DDL format. 

 

.. versionadded:: 2.4.0 

 

Parameters 

---------- 

json : :class:`~pyspark.sql.Column` or str 

a JSON string or a foldable string column containing a JSON string. 

options : dict, optional 

options to control parsing. accepts the same options as the JSON datasource. 

See `Data Source Option <https://spark.apache.org/docs/latest/sql-data-sources-json.html#data-source-option>`_ 

in the version you use. 

 

.. # noqa 

 

.. versionchanged:: 3.0 

It accepts `options` parameter to control schema inferring. 

 

Examples 

-------- 

>>> df = spark.range(1) 

>>> df.select(schema_of_json(lit('{"a": 0}')).alias("json")).collect() 

[Row(json='STRUCT<`a`: BIGINT>')] 

>>> schema = schema_of_json('{a: 1}', {'allowUnquotedFieldNames':'true'}) 

>>> df.select(schema.alias("json")).collect() 

[Row(json='STRUCT<`a`: BIGINT>')] 

""" 

if isinstance(json, str): 

col = _create_column_from_literal(json) 

3786 ↛ 3789line 3786 didn't jump to line 3789, because the condition on line 3786 was never false elif isinstance(json, Column): 

col = _to_java_column(json) 

else: 

raise TypeError("schema argument should be a column or string") 

 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.schema_of_json(col, _options_to_str(options)) 

return Column(jc) 

 

 

def schema_of_csv(csv, options=None): 

""" 

Parses a CSV string and infers its schema in DDL format. 

 

.. versionadded:: 3.0.0 

 

Parameters 

---------- 

csv : :class:`~pyspark.sql.Column` or str 

a CSV string or a foldable string column containing a CSV string. 

options : dict, optional 

options to control parsing. accepts the same options as the CSV datasource. 

See `Data Source Option <https://spark.apache.org/docs/latest/sql-data-sources-csv.html#data-source-option>`_ 

in the version you use. 

 

.. # noqa 

 

Examples 

-------- 

>>> df = spark.range(1) 

>>> df.select(schema_of_csv(lit('1|a'), {'sep':'|'}).alias("csv")).collect() 

[Row(csv='STRUCT<`_c0`: INT, `_c1`: STRING>')] 

>>> df.select(schema_of_csv('1|a', {'sep':'|'}).alias("csv")).collect() 

[Row(csv='STRUCT<`_c0`: INT, `_c1`: STRING>')] 

""" 

if isinstance(csv, str): 

col = _create_column_from_literal(csv) 

3823 ↛ 3826line 3823 didn't jump to line 3826, because the condition on line 3823 was never false elif isinstance(csv, Column): 

col = _to_java_column(csv) 

else: 

raise TypeError("schema argument should be a column or string") 

 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.schema_of_csv(col, _options_to_str(options)) 

return Column(jc) 

 

 

def to_csv(col, options=None): 

""" 

Converts a column containing a :class:`StructType` into a CSV string. 

Throws an exception, in the case of an unsupported type. 

 

.. versionadded:: 3.0.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column containing a struct. 

options: dict, optional 

options to control converting. accepts the same options as the CSV datasource. 

See `Data Source Option <https://spark.apache.org/docs/latest/sql-data-sources-csv.html#data-source-option>`_ 

in the version you use. 

 

.. # noqa 

 

Examples 

-------- 

>>> from pyspark.sql import Row 

>>> data = [(1, Row(age=2, name='Alice'))] 

>>> df = spark.createDataFrame(data, ("key", "value")) 

>>> df.select(to_csv(df.value).alias("csv")).collect() 

[Row(csv='2,Alice')] 

""" 

 

sc = SparkContext._active_spark_context 

jc = sc._jvm.functions.to_csv(_to_java_column(col), _options_to_str(options)) 

return Column(jc) 

 

 

def size(col): 

""" 

Collection function: returns the length of the array or map stored in the column. 

 

.. versionadded:: 1.5.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

 

Examples 

-------- 

>>> df = spark.createDataFrame([([1, 2, 3],),([1],),([],)], ['data']) 

>>> df.select(size(df.data)).collect() 

[Row(size(data)=3), Row(size(data)=1), Row(size(data)=0)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.size(_to_java_column(col))) 

 

 

def array_min(col): 

""" 

Collection function: returns the minimum value of the array. 

 

.. versionadded:: 2.4.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

 

Examples 

-------- 

>>> df = spark.createDataFrame([([2, 1, 3],), ([None, 10, -1],)], ['data']) 

>>> df.select(array_min(df.data).alias('min')).collect() 

[Row(min=1), Row(min=-1)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.array_min(_to_java_column(col))) 

 

 

def array_max(col): 

""" 

Collection function: returns the maximum value of the array. 

 

.. versionadded:: 2.4.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

 

Examples 

-------- 

>>> df = spark.createDataFrame([([2, 1, 3],), ([None, 10, -1],)], ['data']) 

>>> df.select(array_max(df.data).alias('max')).collect() 

[Row(max=3), Row(max=10)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.array_max(_to_java_column(col))) 

 

 

def sort_array(col, asc=True): 

""" 

Collection function: sorts the input array in ascending or descending order according 

to the natural ordering of the array elements. Null elements will be placed at the beginning 

of the returned array in ascending order or at the end of the returned array in descending 

order. 

 

.. versionadded:: 1.5.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

asc : bool, optional 

 

Examples 

-------- 

>>> df = spark.createDataFrame([([2, 1, None, 3],),([1],),([],)], ['data']) 

>>> df.select(sort_array(df.data).alias('r')).collect() 

[Row(r=[None, 1, 2, 3]), Row(r=[1]), Row(r=[])] 

>>> df.select(sort_array(df.data, asc=False).alias('r')).collect() 

[Row(r=[3, 2, 1, None]), Row(r=[1]), Row(r=[])] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.sort_array(_to_java_column(col), asc)) 

 

 

def array_sort(col): 

""" 

Collection function: sorts the input array in ascending order. The elements of the input array 

must be orderable. Null elements will be placed at the end of the returned array. 

 

.. versionadded:: 2.4.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

 

Examples 

-------- 

>>> df = spark.createDataFrame([([2, 1, None, 3],),([1],),([],)], ['data']) 

>>> df.select(array_sort(df.data).alias('r')).collect() 

[Row(r=[1, 2, 3, None]), Row(r=[1]), Row(r=[])] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.array_sort(_to_java_column(col))) 

 

 

def shuffle(col): 

""" 

Collection function: Generates a random permutation of the given array. 

 

.. versionadded:: 2.4.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

 

Notes 

----- 

The function is non-deterministic. 

 

Examples 

-------- 

>>> df = spark.createDataFrame([([1, 20, 3, 5],), ([1, 20, None, 3],)], ['data']) 

>>> df.select(shuffle(df.data).alias('s')).collect() # doctest: +SKIP 

[Row(s=[3, 1, 5, 20]), Row(s=[20, None, 3, 1])] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.shuffle(_to_java_column(col))) 

 

 

def reverse(col): 

""" 

Collection function: returns a reversed string or an array with reverse order of elements. 

 

.. versionadded:: 1.5.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('Spark SQL',)], ['data']) 

>>> df.select(reverse(df.data).alias('s')).collect() 

[Row(s='LQS krapS')] 

>>> df = spark.createDataFrame([([2, 1, 3],) ,([1],) ,([],)], ['data']) 

>>> df.select(reverse(df.data).alias('r')).collect() 

[Row(r=[3, 1, 2]), Row(r=[1]), Row(r=[])] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.reverse(_to_java_column(col))) 

 

 

def flatten(col): 

""" 

Collection function: creates a single array from an array of arrays. 

If a structure of nested arrays is deeper than two levels, 

only one level of nesting is removed. 

 

.. versionadded:: 2.4.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

 

Examples 

-------- 

>>> df = spark.createDataFrame([([[1, 2, 3], [4, 5], [6]],), ([None, [4, 5]],)], ['data']) 

>>> df.select(flatten(df.data).alias('r')).collect() 

[Row(r=[1, 2, 3, 4, 5, 6]), Row(r=None)] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.flatten(_to_java_column(col))) 

 

 

def map_keys(col): 

""" 

Collection function: Returns an unordered array containing the keys of the map. 

 

.. versionadded:: 2.3.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

 

Examples 

-------- 

>>> from pyspark.sql.functions import map_keys 

>>> df = spark.sql("SELECT map(1, 'a', 2, 'b') as data") 

>>> df.select(map_keys("data").alias("keys")).show() 

+------+ 

| keys| 

+------+ 

|[1, 2]| 

+------+ 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.map_keys(_to_java_column(col))) 

 

 

def map_values(col): 

""" 

Collection function: Returns an unordered array containing the values of the map. 

 

.. versionadded:: 2.3.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

 

Examples 

-------- 

>>> from pyspark.sql.functions import map_values 

>>> df = spark.sql("SELECT map(1, 'a', 2, 'b') as data") 

>>> df.select(map_values("data").alias("values")).show() 

+------+ 

|values| 

+------+ 

|[a, b]| 

+------+ 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.map_values(_to_java_column(col))) 

 

 

def map_entries(col): 

""" 

Collection function: Returns an unordered array of all entries in the given map. 

 

.. versionadded:: 3.0.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

 

Examples 

-------- 

>>> from pyspark.sql.functions import map_entries 

>>> df = spark.sql("SELECT map(1, 'a', 2, 'b') as data") 

>>> df.select(map_entries("data").alias("entries")).show() 

+----------------+ 

| entries| 

+----------------+ 

|[{1, a}, {2, b}]| 

+----------------+ 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.map_entries(_to_java_column(col))) 

 

 

def map_from_entries(col): 

""" 

Collection function: Returns a map created from the given array of entries. 

 

.. versionadded:: 2.4.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

 

Examples 

-------- 

>>> from pyspark.sql.functions import map_from_entries 

>>> df = spark.sql("SELECT array(struct(1, 'a'), struct(2, 'b')) as data") 

>>> df.select(map_from_entries("data").alias("map")).show() 

+----------------+ 

| map| 

+----------------+ 

|{1 -> a, 2 -> b}| 

+----------------+ 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.map_from_entries(_to_java_column(col))) 

 

 

def array_repeat(col, count): 

""" 

Collection function: creates an array containing a column repeated count times. 

 

.. versionadded:: 2.4.0 

 

Examples 

-------- 

>>> df = spark.createDataFrame([('ab',)], ['data']) 

>>> df.select(array_repeat(df.data, 3).alias('r')).collect() 

[Row(r=['ab', 'ab', 'ab'])] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.array_repeat( 

_to_java_column(col), 

_to_java_column(count) if isinstance(count, Column) else count 

)) 

 

 

def arrays_zip(*cols): 

""" 

Collection function: Returns a merged array of structs in which the N-th struct contains all 

N-th values of input arrays. 

 

.. versionadded:: 2.4.0 

 

Parameters 

---------- 

cols : :class:`~pyspark.sql.Column` or str 

columns of arrays to be merged. 

 

Examples 

-------- 

>>> from pyspark.sql.functions import arrays_zip 

>>> df = spark.createDataFrame([(([1, 2, 3], [2, 3, 4]))], ['vals1', 'vals2']) 

>>> df.select(arrays_zip(df.vals1, df.vals2).alias('zipped')).collect() 

[Row(zipped=[Row(vals1=1, vals2=2), Row(vals1=2, vals2=3), Row(vals1=3, vals2=4)])] 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.arrays_zip(_to_seq(sc, cols, _to_java_column))) 

 

 

def map_concat(*cols): 

"""Returns the union of all the given maps. 

 

.. versionadded:: 2.4.0 

 

Parameters 

---------- 

cols : :class:`~pyspark.sql.Column` or str 

column names or :class:`~pyspark.sql.Column`\\s 

 

Examples 

-------- 

>>> from pyspark.sql.functions import map_concat 

>>> df = spark.sql("SELECT map(1, 'a', 2, 'b') as map1, map(3, 'c') as map2") 

>>> df.select(map_concat("map1", "map2").alias("map3")).show(truncate=False) 

+------------------------+ 

|map3 | 

+------------------------+ 

|{1 -> a, 2 -> b, 3 -> c}| 

+------------------------+ 

""" 

sc = SparkContext._active_spark_context 

4217 ↛ 4218line 4217 didn't jump to line 4218, because the condition on line 4217 was never true if len(cols) == 1 and isinstance(cols[0], (list, set)): 

cols = cols[0] 

jc = sc._jvm.functions.map_concat(_to_seq(sc, cols, _to_java_column)) 

return Column(jc) 

 

 

def sequence(start, stop, step=None): 

""" 

Generate a sequence of integers from `start` to `stop`, incrementing by `step`. 

If `step` is not set, incrementing by 1 if `start` is less than or equal to `stop`, 

otherwise -1. 

 

.. versionadded:: 2.4.0 

 

Examples 

-------- 

>>> df1 = spark.createDataFrame([(-2, 2)], ('C1', 'C2')) 

>>> df1.select(sequence('C1', 'C2').alias('r')).collect() 

[Row(r=[-2, -1, 0, 1, 2])] 

>>> df2 = spark.createDataFrame([(4, -4, -2)], ('C1', 'C2', 'C3')) 

>>> df2.select(sequence('C1', 'C2', 'C3').alias('r')).collect() 

[Row(r=[4, 2, 0, -2, -4])] 

""" 

sc = SparkContext._active_spark_context 

if step is None: 

return Column(sc._jvm.functions.sequence(_to_java_column(start), _to_java_column(stop))) 

else: 

return Column(sc._jvm.functions.sequence( 

_to_java_column(start), _to_java_column(stop), _to_java_column(step))) 

 

 

def from_csv(col, schema, options=None): 

""" 

Parses a column containing a CSV string to a row with the specified schema. 

Returns `null`, in the case of an unparseable string. 

 

.. versionadded:: 3.0.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

string column in CSV format 

schema :class:`~pyspark.sql.Column` or str 

a string with schema in DDL format to use when parsing the CSV column. 

options : dict, optional 

options to control parsing. accepts the same options as the CSV datasource. 

See `Data Source Option <https://spark.apache.org/docs/latest/sql-data-sources-csv.html#data-source-option>`_ 

in the version you use. 

 

.. # noqa 

 

Examples 

-------- 

>>> data = [("1,2,3",)] 

>>> df = spark.createDataFrame(data, ("value",)) 

>>> df.select(from_csv(df.value, "a INT, b INT, c INT").alias("csv")).collect() 

[Row(csv=Row(a=1, b=2, c=3))] 

>>> value = data[0][0] 

>>> df.select(from_csv(df.value, schema_of_csv(value)).alias("csv")).collect() 

[Row(csv=Row(_c0=1, _c1=2, _c2=3))] 

>>> data = [(" abc",)] 

>>> df = spark.createDataFrame(data, ("value",)) 

>>> options = {'ignoreLeadingWhiteSpace': True} 

>>> df.select(from_csv(df.value, "s string", options).alias("csv")).collect() 

[Row(csv=Row(s='abc'))] 

""" 

 

sc = SparkContext._active_spark_context 

if isinstance(schema, str): 

schema = _create_column_from_literal(schema) 

4287 ↛ 4290line 4287 didn't jump to line 4290, because the condition on line 4287 was never false elif isinstance(schema, Column): 

schema = _to_java_column(schema) 

else: 

raise TypeError("schema argument should be a column or string") 

 

jc = sc._jvm.functions.from_csv(_to_java_column(col), schema, _options_to_str(options)) 

return Column(jc) 

 

 

def _unresolved_named_lambda_variable(*name_parts): 

""" 

Create `o.a.s.sql.expressions.UnresolvedNamedLambdaVariable`, 

convert it to o.s.sql.Column and wrap in Python `Column` 

 

Parameters 

---------- 

name_parts : str 

""" 

sc = SparkContext._active_spark_context 

name_parts_seq = _to_seq(sc, name_parts) 

expressions = sc._jvm.org.apache.spark.sql.catalyst.expressions 

return Column( 

sc._jvm.Column( 

expressions.UnresolvedNamedLambdaVariable(name_parts_seq) 

) 

) 

 

 

def _get_lambda_parameters(f): 

import inspect 

 

signature = inspect.signature(f) 

parameters = signature.parameters.values() 

 

# We should exclude functions that use 

# variable args and keyword argnames 

# as well as keyword only args 

supported_parameter_types = { 

inspect.Parameter.POSITIONAL_OR_KEYWORD, 

inspect.Parameter.POSITIONAL_ONLY, 

} 

 

# Validate that 

# function arity is between 1 and 3 

if not (1 <= len(parameters) <= 3): 

raise ValueError( 

"f should take between 1 and 3 arguments, but provided function takes {}".format( 

len(parameters) 

) 

) 

 

# and all arguments can be used as positional 

if not all(p.kind in supported_parameter_types for p in parameters): 

raise ValueError( 

"f should use only POSITIONAL or POSITIONAL OR KEYWORD arguments" 

) 

 

return parameters 

 

 

def _create_lambda(f): 

""" 

Create `o.a.s.sql.expressions.LambdaFunction` corresponding 

to transformation described by f 

 

:param f: A Python of one of the following forms: 

- (Column) -> Column: ... 

- (Column, Column) -> Column: ... 

- (Column, Column, Column) -> Column: ... 

""" 

parameters = _get_lambda_parameters(f) 

 

sc = SparkContext._active_spark_context 

expressions = sc._jvm.org.apache.spark.sql.catalyst.expressions 

 

argnames = ["x", "y", "z"] 

args = [ 

_unresolved_named_lambda_variable( 

expressions.UnresolvedNamedLambdaVariable.freshVarName(arg) 

) 

for arg in argnames[: len(parameters)] 

] 

 

result = f(*args) 

 

if not isinstance(result, Column): 

raise ValueError("f should return Column, got {}".format(type(result))) 

 

jexpr = result._jc.expr() 

jargs = _to_seq(sc, [arg._jc.expr() for arg in args]) 

 

return expressions.LambdaFunction(jexpr, jargs, False) 

 

 

def _invoke_higher_order_function(name, cols, funs): 

""" 

Invokes expression identified by name, 

(relative to ```org.apache.spark.sql.catalyst.expressions``) 

and wraps the result with Column (first Scala one, then Python). 

 

:param name: Name of the expression 

:param cols: a list of columns 

:param funs: a list of((*Column) -> Column functions. 

 

:return: a Column 

""" 

sc = SparkContext._active_spark_context 

expressions = sc._jvm.org.apache.spark.sql.catalyst.expressions 

expr = getattr(expressions, name) 

 

jcols = [_to_java_column(col).expr() for col in cols] 

jfuns = [_create_lambda(f) for f in funs] 

 

return Column(sc._jvm.Column(expr(*jcols + jfuns))) 

 

 

def transform(col, f): 

""" 

Returns an array of elements after applying a transformation to each element in the input array. 

 

.. versionadded:: 3.1.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

f : function 

a function that is applied to each element of the input array. 

Can take one of the following forms: 

 

- Unary ``(x: Column) -> Column: ...`` 

- Binary ``(x: Column, i: Column) -> Column...``, where the second argument is 

a 0-based index of the element. 

 

and can use methods of :class:`~pyspark.sql.Column`, functions defined in 

:py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. 

Python ``UserDefinedFunctions`` are not supported 

(`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(1, [1, 2, 3, 4])], ("key", "values")) 

>>> df.select(transform("values", lambda x: x * 2).alias("doubled")).show() 

+------------+ 

| doubled| 

+------------+ 

|[2, 4, 6, 8]| 

+------------+ 

 

>>> def alternate(x, i): 

... return when(i % 2 == 0, x).otherwise(-x) 

>>> df.select(transform("values", alternate).alias("alternated")).show() 

+--------------+ 

| alternated| 

+--------------+ 

|[1, -2, 3, -4]| 

+--------------+ 

""" 

return _invoke_higher_order_function("ArrayTransform", [col], [f]) 

 

 

def exists(col, f): 

""" 

Returns whether a predicate holds for one or more elements in the array. 

 

.. versionadded:: 3.1.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

f : function 

``(x: Column) -> Column: ...`` returning the Boolean expression. 

Can use methods of :class:`~pyspark.sql.Column`, functions defined in 

:py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. 

Python ``UserDefinedFunctions`` are not supported 

(`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). 

:return: a :class:`~pyspark.sql.Column` 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(1, [1, 2, 3, 4]), (2, [3, -1, 0])],("key", "values")) 

>>> df.select(exists("values", lambda x: x < 0).alias("any_negative")).show() 

+------------+ 

|any_negative| 

+------------+ 

| false| 

| true| 

+------------+ 

""" 

return _invoke_higher_order_function("ArrayExists", [col], [f]) 

 

 

def forall(col, f): 

""" 

Returns whether a predicate holds for every element in the array. 

 

.. versionadded:: 3.1.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

f : function 

``(x: Column) -> Column: ...`` returning the Boolean expression. 

Can use methods of :class:`~pyspark.sql.Column`, functions defined in 

:py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. 

Python ``UserDefinedFunctions`` are not supported 

(`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

 

Examples 

-------- 

>>> df = spark.createDataFrame( 

... [(1, ["bar"]), (2, ["foo", "bar"]), (3, ["foobar", "foo"])], 

... ("key", "values") 

... ) 

>>> df.select(forall("values", lambda x: x.rlike("foo")).alias("all_foo")).show() 

+-------+ 

|all_foo| 

+-------+ 

| false| 

| false| 

| true| 

+-------+ 

""" 

return _invoke_higher_order_function("ArrayForAll", [col], [f]) 

 

 

def filter(col, f): 

""" 

Returns an array of elements for which a predicate holds in a given array. 

 

.. versionadded:: 3.1.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

f : function 

A function that returns the Boolean expression. 

Can take one of the following forms: 

 

- Unary ``(x: Column) -> Column: ...`` 

- Binary ``(x: Column, i: Column) -> Column...``, where the second argument is 

a 0-based index of the element. 

 

and can use methods of :class:`~pyspark.sql.Column`, functions defined in 

:py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. 

Python ``UserDefinedFunctions`` are not supported 

(`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

 

Examples 

-------- 

>>> df = spark.createDataFrame( 

... [(1, ["2018-09-20", "2019-02-03", "2019-07-01", "2020-06-01"])], 

... ("key", "values") 

... ) 

>>> def after_second_quarter(x): 

... return month(to_date(x)) > 6 

>>> df.select( 

... filter("values", after_second_quarter).alias("after_second_quarter") 

... ).show(truncate=False) 

+------------------------+ 

|after_second_quarter | 

+------------------------+ 

|[2018-09-20, 2019-07-01]| 

+------------------------+ 

""" 

return _invoke_higher_order_function("ArrayFilter", [col], [f]) 

 

 

def aggregate(col, initialValue, merge, finish=None): 

""" 

Applies a binary operator to an initial state and all elements in the array, 

and reduces this to a single state. The final state is converted into the final result 

by applying a finish function. 

 

Both functions can use methods of :class:`~pyspark.sql.Column`, functions defined in 

:py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. 

Python ``UserDefinedFunctions`` are not supported 

(`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). 

 

.. versionadded:: 3.1.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

initialValue : :class:`~pyspark.sql.Column` or str 

initial value. Name of column or expression 

merge : function 

a binary function ``(acc: Column, x: Column) -> Column...`` returning expression 

of the same type as ``zero`` 

finish : function 

an optional unary function ``(x: Column) -> Column: ...`` 

used to convert accumulated value. 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(1, [20.0, 4.0, 2.0, 6.0, 10.0])], ("id", "values")) 

>>> df.select(aggregate("values", lit(0.0), lambda acc, x: acc + x).alias("sum")).show() 

+----+ 

| sum| 

+----+ 

|42.0| 

+----+ 

 

>>> def merge(acc, x): 

... count = acc.count + 1 

... sum = acc.sum + x 

... return struct(count.alias("count"), sum.alias("sum")) 

>>> df.select( 

... aggregate( 

... "values", 

... struct(lit(0).alias("count"), lit(0.0).alias("sum")), 

... merge, 

... lambda acc: acc.sum / acc.count, 

... ).alias("mean") 

... ).show() 

+----+ 

|mean| 

+----+ 

| 8.4| 

+----+ 

""" 

if finish is not None: 

return _invoke_higher_order_function( 

"ArrayAggregate", 

[col, initialValue], 

[merge, finish] 

) 

 

else: 

return _invoke_higher_order_function( 

"ArrayAggregate", 

[col, initialValue], 

[merge] 

) 

 

 

def zip_with(left, right, f): 

""" 

Merge two given arrays, element-wise, into a single array using a function. 

If one array is shorter, nulls are appended at the end to match the length of the longer 

array, before applying the function. 

 

.. versionadded:: 3.1.0 

 

Parameters 

---------- 

left : :class:`~pyspark.sql.Column` or str 

name of the first column or expression 

right : :class:`~pyspark.sql.Column` or str 

name of the second column or expression 

f : function 

a binary function ``(x1: Column, x2: Column) -> Column...`` 

Can use methods of :class:`~pyspark.sql.Column`, functions defined in 

:py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. 

Python ``UserDefinedFunctions`` are not supported 

(`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(1, [1, 3, 5, 8], [0, 2, 4, 6])], ("id", "xs", "ys")) 

>>> df.select(zip_with("xs", "ys", lambda x, y: x ** y).alias("powers")).show(truncate=False) 

+---------------------------+ 

|powers | 

+---------------------------+ 

|[1.0, 9.0, 625.0, 262144.0]| 

+---------------------------+ 

 

>>> df = spark.createDataFrame([(1, ["foo", "bar"], [1, 2, 3])], ("id", "xs", "ys")) 

>>> df.select(zip_with("xs", "ys", lambda x, y: concat_ws("_", x, y)).alias("xs_ys")).show() 

+-----------------+ 

| xs_ys| 

+-----------------+ 

|[foo_1, bar_2, 3]| 

+-----------------+ 

""" 

return _invoke_higher_order_function("ZipWith", [left, right], [f]) 

 

 

def transform_keys(col, f): 

""" 

Applies a function to every key-value pair in a map and returns 

a map with the results of those applications as the new keys for the pairs. 

 

.. versionadded:: 3.1.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

f : function 

a binary function ``(k: Column, v: Column) -> Column...`` 

Can use methods of :class:`~pyspark.sql.Column`, functions defined in 

:py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. 

Python ``UserDefinedFunctions`` are not supported 

(`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(1, {"foo": -2.0, "bar": 2.0})], ("id", "data")) 

>>> df.select(transform_keys( 

... "data", lambda k, _: upper(k)).alias("data_upper") 

... ).show(truncate=False) 

+-------------------------+ 

|data_upper | 

+-------------------------+ 

|{BAR -> 2.0, FOO -> -2.0}| 

+-------------------------+ 

""" 

return _invoke_higher_order_function("TransformKeys", [col], [f]) 

 

 

def transform_values(col, f): 

""" 

Applies a function to every key-value pair in a map and returns 

a map with the results of those applications as the new values for the pairs. 

 

.. versionadded:: 3.1.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

f : function 

a binary function ``(k: Column, v: Column) -> Column...`` 

Can use methods of :class:`~pyspark.sql.Column`, functions defined in 

:py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. 

Python ``UserDefinedFunctions`` are not supported 

(`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(1, {"IT": 10.0, "SALES": 2.0, "OPS": 24.0})], ("id", "data")) 

>>> df.select(transform_values( 

... "data", lambda k, v: when(k.isin("IT", "OPS"), v + 10.0).otherwise(v) 

... ).alias("new_data")).show(truncate=False) 

+---------------------------------------+ 

|new_data | 

+---------------------------------------+ 

|{OPS -> 34.0, IT -> 20.0, SALES -> 2.0}| 

+---------------------------------------+ 

""" 

return _invoke_higher_order_function("TransformValues", [col], [f]) 

 

 

def map_filter(col, f): 

""" 

Returns a map whose key-value pairs satisfy a predicate. 

 

.. versionadded:: 3.1.0 

 

Parameters 

---------- 

col : :class:`~pyspark.sql.Column` or str 

name of column or expression 

f : function 

a binary function ``(k: Column, v: Column) -> Column...`` 

Can use methods of :class:`~pyspark.sql.Column`, functions defined in 

:py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. 

Python ``UserDefinedFunctions`` are not supported 

(`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

 

Examples 

-------- 

>>> df = spark.createDataFrame([(1, {"foo": 42.0, "bar": 1.0, "baz": 32.0})], ("id", "data")) 

>>> df.select(map_filter( 

... "data", lambda _, v: v > 30.0).alias("data_filtered") 

... ).show(truncate=False) 

+--------------------------+ 

|data_filtered | 

+--------------------------+ 

|{baz -> 32.0, foo -> 42.0}| 

+--------------------------+ 

""" 

return _invoke_higher_order_function("MapFilter", [col], [f]) 

 

 

def map_zip_with(col1, col2, f): 

""" 

Merge two given maps, key-wise into a single map using a function. 

 

.. versionadded:: 3.1.0 

 

Parameters 

---------- 

col1 : :class:`~pyspark.sql.Column` or str 

name of the first column or expression 

col2 : :class:`~pyspark.sql.Column` or str 

name of the second column or expression 

f : function 

a ternary function ``(k: Column, v1: Column, v2: Column) -> Column...`` 

Can use methods of :class:`~pyspark.sql.Column`, functions defined in 

:py:mod:`pyspark.sql.functions` and Scala ``UserDefinedFunctions``. 

Python ``UserDefinedFunctions`` are not supported 

(`SPARK-27052 <https://issues.apache.org/jira/browse/SPARK-27052>`__). 

 

Returns 

------- 

:class:`~pyspark.sql.Column` 

 

Examples 

-------- 

>>> df = spark.createDataFrame([ 

... (1, {"IT": 24.0, "SALES": 12.00}, {"IT": 2.0, "SALES": 1.4})], 

... ("id", "base", "ratio") 

... ) 

>>> df.select(map_zip_with( 

... "base", "ratio", lambda k, v1, v2: round(v1 * v2, 2)).alias("updated_data") 

... ).show(truncate=False) 

+---------------------------+ 

|updated_data | 

+---------------------------+ 

|{SALES -> 16.8, IT -> 48.0}| 

+---------------------------+ 

""" 

return _invoke_higher_order_function("MapZipWith", [col1, col2], [f]) 

 

 

# ---------------------- Partition transform functions -------------------------------- 

 

def years(col): 

""" 

Partition transform function: A transform for timestamps and dates 

to partition data into years. 

 

.. versionadded:: 3.1.0 

 

Examples 

-------- 

>>> df.writeTo("catalog.db.table").partitionedBy( # doctest: +SKIP 

... years("ts") 

... ).createOrReplace() 

 

Notes 

----- 

This function can be used only in combination with 

:py:meth:`~pyspark.sql.readwriter.DataFrameWriterV2.partitionedBy` 

method of the `DataFrameWriterV2`. 

 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.years(_to_java_column(col))) 

 

 

def months(col): 

""" 

Partition transform function: A transform for timestamps and dates 

to partition data into months. 

 

.. versionadded:: 3.1.0 

 

Examples 

-------- 

>>> df.writeTo("catalog.db.table").partitionedBy( 

... months("ts") 

... ).createOrReplace() # doctest: +SKIP 

 

Notes 

----- 

This function can be used only in combination with 

:py:meth:`~pyspark.sql.readwriter.DataFrameWriterV2.partitionedBy` 

method of the `DataFrameWriterV2`. 

 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.months(_to_java_column(col))) 

 

 

def days(col): 

""" 

Partition transform function: A transform for timestamps and dates 

to partition data into days. 

 

.. versionadded:: 3.1.0 

 

Examples 

-------- 

>>> df.writeTo("catalog.db.table").partitionedBy( # doctest: +SKIP 

... days("ts") 

... ).createOrReplace() 

 

Notes 

----- 

This function can be used only in combination with 

:py:meth:`~pyspark.sql.readwriter.DataFrameWriterV2.partitionedBy` 

method of the `DataFrameWriterV2`. 

 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.days(_to_java_column(col))) 

 

 

def hours(col): 

""" 

Partition transform function: A transform for timestamps 

to partition data into hours. 

 

.. versionadded:: 3.1.0 

 

Examples 

-------- 

>>> df.writeTo("catalog.db.table").partitionedBy( # doctest: +SKIP 

... hours("ts") 

... ).createOrReplace() 

 

Notes 

----- 

This function can be used only in combination with 

:py:meth:`~pyspark.sql.readwriter.DataFrameWriterV2.partitionedBy` 

method of the `DataFrameWriterV2`. 

 

""" 

sc = SparkContext._active_spark_context 

return Column(sc._jvm.functions.hours(_to_java_column(col))) 

 

 

def bucket(numBuckets, col): 

""" 

Partition transform function: A transform for any type that partitions 

by a hash of the input column. 

 

.. versionadded:: 3.1.0 

 

Examples 

-------- 

>>> df.writeTo("catalog.db.table").partitionedBy( # doctest: +SKIP 

... bucket(42, "ts") 

... ).createOrReplace() 

 

Notes 

----- 

This function can be used only in combination with 

:py:meth:`~pyspark.sql.readwriter.DataFrameWriterV2.partitionedBy` 

method of the `DataFrameWriterV2`. 

 

""" 

4958 ↛ 4959line 4958 didn't jump to line 4959, because the condition on line 4958 was never true if not isinstance(numBuckets, (int, Column)): 

raise TypeError( 

"numBuckets should be a Column or an int, got {}".format(type(numBuckets)) 

) 

 

sc = SparkContext._active_spark_context 

numBuckets = ( 

_create_column_from_literal(numBuckets) 

if isinstance(numBuckets, int) 

else _to_java_column(numBuckets) 

) 

return Column(sc._jvm.functions.bucket(numBuckets, _to_java_column(col))) 

 

 

# ---------------------------- User Defined Function ---------------------------------- 

 

def udf(f=None, returnType=StringType()): 

"""Creates a user defined function (UDF). 

 

.. versionadded:: 1.3.0 

 

Parameters 

---------- 

f : function 

python function if used as a standalone function 

returnType : :class:`pyspark.sql.types.DataType` or str 

the return type of the user-defined function. The value can be either a 

:class:`pyspark.sql.types.DataType` object or a DDL-formatted type string. 

 

Examples 

-------- 

>>> from pyspark.sql.types import IntegerType 

>>> slen = udf(lambda s: len(s), IntegerType()) 

>>> @udf 

... def to_upper(s): 

... if s is not None: 

... return s.upper() 

... 

>>> @udf(returnType=IntegerType()) 

... def add_one(x): 

... if x is not None: 

... return x + 1 

... 

>>> df = spark.createDataFrame([(1, "John Doe", 21)], ("id", "name", "age")) 

>>> df.select(slen("name").alias("slen(name)"), to_upper("name"), add_one("age")).show() 

+----------+--------------+------------+ 

|slen(name)|to_upper(name)|add_one(age)| 

+----------+--------------+------------+ 

| 8| JOHN DOE| 22| 

+----------+--------------+------------+ 

 

Notes 

----- 

The user-defined functions are considered deterministic by default. Due to 

optimization, duplicate invocations may be eliminated or the function may even be invoked 

more times than it is present in the query. If your function is not deterministic, call 

`asNondeterministic` on the user defined function. E.g.: 

 

>>> from pyspark.sql.types import IntegerType 

>>> import random 

>>> random_udf = udf(lambda: int(random.random() * 100), IntegerType()).asNondeterministic() 

 

The user-defined functions do not support conditional expressions or short circuiting 

in boolean expressions and it ends up with being executed all internally. If the functions 

can fail on special rows, the workaround is to incorporate the condition into the functions. 

 

The user-defined functions do not take keyword arguments on the calling side. 

""" 

 

# The following table shows most of Python data and SQL type conversions in normal UDFs that 

# are not yet visible to the user. Some of behaviors are buggy and might be changed in the near 

# future. The table might have to be eventually documented externally. 

# Please see SPARK-28131's PR to see the codes in order to generate the table below. 

# 

# +-----------------------------+--------------+----------+------+---------------+--------------------+-----------------------------+----------+----------------------+---------+--------------------+----------------------------+------------+--------------+------------------+----------------------+ # noqa 

# |SQL Type \ Python Value(Type)|None(NoneType)|True(bool)|1(int)| a(str)| 1970-01-01(date)|1970-01-01 00:00:00(datetime)|1.0(float)|array('i', [1])(array)|[1](list)| (1,)(tuple)|bytearray(b'ABC')(bytearray)| 1(Decimal)|{'a': 1}(dict)|Row(kwargs=1)(Row)|Row(namedtuple=1)(Row)| # noqa 

# +-----------------------------+--------------+----------+------+---------------+--------------------+-----------------------------+----------+----------------------+---------+--------------------+----------------------------+------------+--------------+------------------+----------------------+ # noqa 

# | boolean| None| True| None| None| None| None| None| None| None| None| None| None| None| X| X| # noqa 

# | tinyint| None| None| 1| None| None| None| None| None| None| None| None| None| None| X| X| # noqa 

# | smallint| None| None| 1| None| None| None| None| None| None| None| None| None| None| X| X| # noqa 

# | int| None| None| 1| None| None| None| None| None| None| None| None| None| None| X| X| # noqa 

# | bigint| None| None| 1| None| None| None| None| None| None| None| None| None| None| X| X| # noqa 

# | string| None| 'true'| '1'| 'a'|'java.util.Gregor...| 'java.util.Gregor...| '1.0'| '[I@66cbb73a'| '[1]'|'[Ljava.lang.Obje...| '[B@5a51eb1a'| '1'| '{a=1}'| X| X| # noqa 

# | date| None| X| X| X|datetime.date(197...| datetime.date(197...| X| X| X| X| X| X| X| X| X| # noqa 

# | timestamp| None| X| X| X| X| datetime.datetime...| X| X| X| X| X| X| X| X| X| # noqa 

# | float| None| None| None| None| None| None| 1.0| None| None| None| None| None| None| X| X| # noqa 

# | double| None| None| None| None| None| None| 1.0| None| None| None| None| None| None| X| X| # noqa 

# | array<int>| None| None| None| None| None| None| None| [1]| [1]| [1]| [65, 66, 67]| None| None| X| X| # noqa 

# | binary| None| None| None|bytearray(b'a')| None| None| None| None| None| None| bytearray(b'ABC')| None| None| X| X| # noqa 

# | decimal(10,0)| None| None| None| None| None| None| None| None| None| None| None|Decimal('1')| None| X| X| # noqa 

# | map<string,int>| None| None| None| None| None| None| None| None| None| None| None| None| {'a': 1}| X| X| # noqa 

# | struct<_1:int>| None| X| X| X| X| X| X| X|Row(_1=1)| Row(_1=1)| X| X| Row(_1=None)| Row(_1=1)| Row(_1=1)| # noqa 

# +-----------------------------+--------------+----------+------+---------------+--------------------+-----------------------------+----------+----------------------+---------+--------------------+----------------------------+------------+--------------+------------------+----------------------+ # noqa 

# 

# Note: DDL formatted string is used for 'SQL Type' for simplicity. This string can be 

# used in `returnType`. 

# Note: The values inside of the table are generated by `repr`. 

# Note: 'X' means it throws an exception during the conversion. 

# Note: Python 3.7.3 is used. 

 

# decorator @udf, @udf(), @udf(dataType()) 

if f is None or isinstance(f, (str, DataType)): 

# If DataType has been passed as a positional argument 

# for decorator use it as a returnType 

return_type = f or returnType 

return functools.partial(_create_udf, returnType=return_type, 

evalType=PythonEvalType.SQL_BATCHED_UDF) 

else: 

return _create_udf(f=f, returnType=returnType, 

evalType=PythonEvalType.SQL_BATCHED_UDF) 

 

 

def _test(): 

import doctest 

from pyspark.sql import Row, SparkSession 

import pyspark.sql.functions 

globs = pyspark.sql.functions.__dict__.copy() 

spark = SparkSession.builder\ 

.master("local[4]")\ 

.appName("sql.functions tests")\ 

.getOrCreate() 

sc = spark.sparkContext 

globs['sc'] = sc 

globs['spark'] = spark 

globs['df'] = spark.createDataFrame([Row(age=2, name='Alice'), Row(age=5, name='Bob')]) 

(failure_count, test_count) = doctest.testmod( 

pyspark.sql.functions, globs=globs, 

optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE) 

spark.stop() 

5087 ↛ 5088line 5087 didn't jump to line 5088, because the condition on line 5087 was never true if failure_count: 

sys.exit(-1) 

 

 

if __name__ == "__main__": 

_test()