search
Search
Login
Map of Data Science
menu
menu search toc more_vert
Robocat
Guest 0reps
Sign up
Log in
account_circleMy Profile homeAbout paidPricing
emailContact us
exit_to_appLog out
Map of data science
Thanks for the thanks!
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
help Ask a question
Share on Twitter
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to
A
A
brightness_medium
share
arrow_backShare
Twitter
Facebook

PySpark SQL Functions | instr method

Machine Learning
chevron_right
PySpark
chevron_right
Documentation
chevron_right
PySpark SQL Functions
schedule Jul 1, 2022
Last updated
local_offer PySpark
Tags
map
Check out the interactive map of data science

PySpark SQL Functions' instr(~) method returns a new PySpark Column holding the position of the first occurrence of the specified substring in each value of the specified column.

WARNING

The position is not index-based, and starts from 1 instead of 0.

Parameters

1. str | string or Column

The column to perform the operation on.

2. substr | string

The substring of which to check the position.

Return Value

A PySpark DataFrame.

Examples

Consider the following PySpark DataFrame:

df = spark.createDataFrame([("ABA",), ("BBB",), ("CCC",), (None,)], ["x",])
df.show()
+----+
| x|
+----+
| ABA|
| BBB|
| CCC|
|null|
+----+

Getting the position of the first occurrence of a substring in PySpark Column

To get the position of the first occurrence of the substring "B" in column x, use the instr(~) method:

df.select(F.instr("x", "B")).show()
+-----------+
|instr(x, B)|
+-----------+
| 2|
| 1|
| 0|
| null|
+-----------+

Here, note the following:

  • we see 2 returned for the column value "ABA" because the substring "B" occurs in the 2nd position - remember, this method counts position from 1 instead of 0.

  • if the substring does not exist in the string, then a value of 0 is returned. This is the case for "Cathy" because this string does not include "B".

  • if the string is null, then the result will also be null.

robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!