185k views
1 vote
How to Create a New Column Based on the Value of Another Column in Pandas?

1 Answer

4 votes

Final answer:

To create a new column in a Pandas DataFrame based on the value of another column, you can use the .apply() method with a lambda function or a custom function. This will perform your specified operation on each element of the original column to derive the new column's values.

Step-by-step explanation:

To create a new column in a Pandas DataFrame based on the values of another column, you can use the .apply() method or a lambda function. Assume you have a DataFrame df with a column 'A', and you want to create a new column 'B' where the value is twice the value in column 'A'. Here's an example of how you can do this:

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3, 4]})
df['B'] = df['A'].apply(lambda x: x * 2)

This will result in DataFrame df having a new column 'B' with values [2, 4, 6, 8].

You can also use a function to define more complex operations:

def double_value(x):
return x * 2
df['B'] = df['A'].apply(double_value)

This would achieve the same result as the lambda function example above.

User Fabian Barkhau
by
8.8k points