Wednesday, November 18, 2020

Python — How to update multiple columns at once in dataframe?


W
orking as Python developer, data analysts or data scientists for any organisation then it is very important for you to know how to play with Dataframes. 



We understand, we can add a column to a dataframe and update its values to the values returned from a function or other dataframe column’s values as given below -

Problem — The actual function is returning two items, and I want to put these two items in two different new columns.

How to update multiple columns in Dataframe? If you want to update multiple columns in dataframe then you should make sure that these columns must be present in your dataframe. In case, updated columns are not in your dataframe, you have to create them as given below -

With the help of Pseudo code technique, we can update multiple columns at once. Pseudo code is a term which is often used in programming and algorithm based fields. It is a methodology that allows the programmer to represent the implementation of an algorithm.

Advantages of Pseudocode

  • Improves the readability of any approach. It’s one of the best approaches to start implementation of an algorithm.
  • Acts as a bridge between the program and the algorithm or flowchart. Also works as a rough documentation, so the program of one developer can be understood easily when a pseudo code is written out. In industries, the approach of documentation is essential. And that’s where a pseudo-code proves vital.
  • The main goal of a pseudo code is to explain what exactly each line of a program should do, hence making the code construction phase easier for the programmer.

Now, we have to create a function to return multiple values as given below -

Note: df.loc takes two parameters, a list of rows you want to work on — in this case — which means all of them, and a list of columns - [‘Square of Num’, ‘Cube of Num’].

We can call the function directly as given below —

Now, this example shows you, how to update multiple columns inside your dataframe. Keep in mind that if you’re munging data, you should most probably be using pandas because it has far more elegant tools than the pure Python workarounds.

No comments:

Post a Comment

Popular Posts