Home > front end >  Dataframe multiply column (array) with scalar
Dataframe multiply column (array) with scalar

Time:01-04

I have a dataframe with many columns, especially with a column contains a array value like:

Name  City  Details

Nicolas  Paris [1 5 3 2]

Adam     Rome  [5 3 45 0]

I try to multiply the Details column with scalar like

df_results.loc[:,'Values'] = df_results.loc[:,'Values'].mul(5)

# or like that
df_results.loc[:,'Values'] = df_results['Values'] * 5

but i get this message can't multiply sequence by non-int of type 'float'

expected results

Name  City  Details

Nicolas  Paris [5 25 15 10]

Adam     Rome  [25 15 225 0]

any Ideas?

CodePudding user response:

Use applymap with a condition that checks the type of the cell:

x = [
    ["Name","City","Details"],
    ["Nicolas","Paris",[1,5,3,2]],
    ["Adam","Rome",[5,3,45,0]],
]

import pandas as pd

df = pd.DataFrame(x)

df.applymap(lambda x: [y*2 for y in x] if isinstance(x, list) else x)

If it's a list, use list comprehension to apply some operation (like multiply by 2)

CodePudding user response:

can do that also by using numpy:

import pandas as pd
import numpy as np

df=pd.DataFrame(columns=['Name','City','Details'])
df['Name']=['Nicolas','Adam']
df['City']=['Paris','NY']
df['Details']=[[1,5,3,2],[5,3,45,0]]


df['Details']=[np.array(i)*5 for i in df['Details'].values]

result:

      Name   City           Details
0  Nicolas  Paris   [5, 25, 15, 10]
1     Adam     NY  [25, 15, 225, 0]

CodePudding user response:

If you just want to multiply the "Details" column, you can simplify DSteman's answer by using apply instead of applymap and not checking whether it is a list or not:

import pandas as pd

df_results = pd.DataFrame({
    'Name': ['Nicolas', 'Adam'],
    'City': ['Paris', 'Rome'],
    'Details': [[1, 5, 3, 2], [5, 3, 45, 0]]
})
df_results['Details'] = df_results['Details'].apply(lambda x: [value * 5 for value in x])

Resulting in:

      Name   City           Details
0  Nicolas  Paris   [5, 25, 15, 10]
1     Adam   Rome  [25, 15, 225, 0]

CodePudding user response:

df['Details'] = df['Details'].map(lambda x: [value * 5 for value in x])
  • Related