I ran into a very odd error today. I am trying to add the values of one column to multiple columns but pandas is throwing a memory error. I looked around but I must be wording the problem poorly because I found a bunch of pd.concat
questions.
Imagine the following data frame:
import pandas as pd
df = pd.DataFrame({c1:[100,200,300],c2:[10,20,30],c3:[1,2,3]})
I want to reassign columns c1
and c2
so that they become their original values plus c3
. I thought this would work:
df[['c1','c2']] = df[['c1','c2']] + df['c3']
---------------------------------------------------------------------------
MemoryError
I solved it doing the following, but there has to be a better solution.
df[['c1','c2']].apply(lambda x: x + df['c3'])
What am I missing? Is there a way to use an axis
argument to make the first method work? Is there a way to use .sum()
to achieve this?
@ALollz posted the solution as a comment, so here it is as an answer. Hope it helps someone in the future:
df[['c1','c2']] = df[['c1','c2']].add(df['c3'], axis=0)
I was not specifying the axis argument, hence the importance of .add()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.