Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Dataframe subtract a value from each list of a row

I have a data frame consisting of lists as elements. I want to subtract a value from each list and create a new column.
My code:

df = pd.DataFrame({'A':[[1,2],[4,5,6]]})
df
           A
0     [1, 2]
1  [4, 5, 6]

# lets substract 1 from each list
val = 1
df['A_new'] = df['A'].apply(lambda x:[a-b for a,b in zip(x[0],[val]*len(x[0]))],axis=1)

Present solution:

IndexError: index 3 is out of bounds for axis 0 with size 2

Expected solution:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df
           A      A_new
0     [1, 2]     [0, 1]
1  [4, 5, 6]  [3, 4, 5]

>Solution :

Convert to numpy array

df['A_new'] = df.A.map(np.array)-1
Out[455]: 
0       [0, 1]
1    [3, 4, 5]
Name: A, dtype: object
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading