Loop through Dataframe in Python
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-09-2020 06:08 PM
Hello,
Imagine you have a dataframe with cols: A, B, C. I want to add a column D based on some calculations of columns B and C of the previous record of the df. Which is the best way of doing this? I am trying to avoid looping through the df. I am using python.
Thanks.
Fernando.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-09-2020 06:52 PM
I would probably use a window function within pyspark.
Link to Databricks blog: https://databricks.com/blog/2015/07/15/introducing-window-functions-in-spark-sql.htmlAnother option is to use lag or lead columns to help you capture the data in the relative position you desire.
You can find theme here in the SQL functions list: https://docs.databricks.com/spark/latest/spark-sql/language-manual/functions.html
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-02-2021 11:25 PM
Iterating through pandas dataFrame objects is generally slow. Pandas Iteration beats the whole purpose of using DataFrame. It is an anti-pattern and is something you should only do when you have exhausted every other option. It is better look for a List Comprehensions , vectorized solution or DataFrame.apply() method.
Pandas DataFrame loop using list comprehension:
result = [(x, y,z) for x, y,z in zip(df['Name'], df['Promoted'],df['Grade'])]