Home > Software engineering >  How do you add new columns with pandas library?
How do you add new columns with pandas library?

Time:01-01

This is an updated version of a previous question

I was having some trouble with csv files and pandas. I would like to create a new column, that being a multiplication of the previous one. For instance ['price', 'pricex2'] [[2,4],[6,12]] and so on, how could I do that?

I've got this piece of code which does not add a new column, it is suposed to update the current one, and evenso it does not work.

   df = pd.read_csv(csvfile)
   df['Jewerly_name_price'] = df['Jewerly_name_price']*2
   print(df)

Plus, I have a € at the end of each price and to multiply the values x2 I would need to get rid of that, I got answered to this already but I don't know how to implement it in the addition of the new column.

price = 2.45€ 
numericalPrice = float(price[:-1]

CodePudding user response:

If you have:

df = pd.DataFrame({'col0':[1,2,3]})

You can add a new column col1 to the df by:

df = df.assign(col1 = df.col0*2)

You can also do more complicated things, such as:

df = pd.DataFrame({'col0':["1€","2€","3€"]})
df = df.assign(col1 = df.col0.apply(lambda row: f'{int(row[:-1])*2}€'))

where the Define an example dataframe

Define a function to do the price calculation

Apply the function to get price calculated

  • Related