Python Forum
Adding a new column to a Panda Data Frame
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Adding a new column to a Panda Data Frame
#1
Please consider the following Python code:
import pandas as pd


data = {
  "l1": [50, 100, 150, 200, 250, -350, 450],
  "l2": [100, 120, 150, 190, 240, 200, 500],
}

#load data into a DataFrame object:
df = pd.DataFrame(data)
I want to write code to add a new column to the data frame df where the new values are the larger of the values in l1 and l2. I can do this using a loop with the following code:
maxValue = []
limit = len ( df )
for i in range( limit ):
    if df.l1[i] > df.l2[i]:
        maxValue.append( df.l1[i] )
    else:
         maxValue.append( df.l2[i] )
df['l3'] = maxValue
However, I believe there should be a better way. I tired this:
df['l3'] = df['l1'] if df['l1'] > df['l2'] else df['l2']
This produced the following error message:
Error:
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py", line 1478, in __nonzero__ raise ValueError( ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
What is the right way to add the new column l3 to df?
Reply
#2
with numpy, like ifesle statment in R...
df['l3'] = np.where(df['l1'] > df['l2'], df['l1'],  df['l2'])
Reply
#3
Alternatively
df['l3'] = df.apply(lambda row: max(row.l1,row.l2), axis=1)
Output:
l1 l2 l3 0 50 100 100 1 100 120 120 2 150 150 150 3 200 190 200 4 250 240 250 5 -350 200 200 6 450 500 500
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Grouping in pandas/multi-index data frame Aleqsie 3 689 Jan-06-2024, 03:55 PM
Last Post: deanhystad
  Filtering Data Frame, with another value NewBiee 9 1,414 Aug-21-2023, 10:53 AM
Last Post: NewBiee
  Make unique id in vectorized way based on text data column with similarity scoring ill8 0 894 Dec-12-2022, 03:22 AM
Last Post: ill8
  Exporting data frame to excel dyerlee91 0 1,634 Oct-05-2021, 11:34 AM
Last Post: dyerlee91
  What if a column has about 90% of data as outliers? Asahavey17 1 1,825 Aug-23-2021, 04:55 PM
Last Post: jefsummers
  Pandas Data frame column condition check based on length of the value aditi06 1 2,701 Jul-28-2021, 11:08 AM
Last Post: jefsummers
  grouped data frame glitter 0 1,603 Feb-02-2021, 11:22 AM
Last Post: glitter
  Redistributing column data metro17 2 1,687 Nov-28-2020, 05:53 PM
Last Post: metro17
  how to filter data frame dynamically with the columns psahay 0 2,410 Aug-24-2020, 01:10 PM
Last Post: psahay
  Dropping Rows From A Data Frame Based On A Variable JoeDainton123 1 2,231 Aug-03-2020, 02:05 AM
Last Post: scidam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020