Can't convert 'numpy.int64' object to str implicitly [on hold]


Can't convert 'numpy.int64' object to str implicitly [on hold]



I have 6columns and 35 rows.My numerical column starts at 2nd index.I want to sum all numerical columns and add a new row as 'Total'.


for i in range(2,6,1):
for j in range(35):
df.loc['Total',_]=df.iloc[i,j]+df.iloc[i+1,j+1]



It shows


TypeError: Can't convert 'numpy.int64' object to str implicitly



Can anyone say what wrong I did in this??



This question appears to be off-topic. The users who voted to close gave this specific reason:





Possible duplicate of TypeError: Can't convert 'int' object to str implicitly
– aloisdg
Jun 29 at 9:55




1 Answer
1



Ok first of all: NEVER use loops with pandas, those are really slow and not well optimized for those kind of datasets. There might be some very rare cases where you cannot do otherwise, but most of the time you can just use pandas functions to do what you want.



For example in your case:


df['Total'] = df[list(range(1, 6))].sum(axis=1)



will add a new column Total which is the sum of columns 1 to 5


Total



Edit: Just for demonstration purposes, do not replicate this at home :)
You can do it using loops if you really want to, but pandas object are not supposed to be assigned dynamically that's why you should go back to python data structures:


res = {}
for row in df.index:
res[row] = 0
for col in df.columns[1:]:
res[row] += df.loc[row, col]

df['Total'] = pd.Series(res)





Thanks.I used df.select_dtypes(include=[np.number]).sum().rename('Total').I just wanted to know if this could be done by loop
– Anees
Jun 29 at 9:58



df.select_dtypes(include=[np.number]).sum().rename('Total')





You can do it if you really want to, I edited my previous answer to show you
– Zuma
Jun 29 at 10:12





Actually I want 'Total' as a new row and sum values for each numerical column.
– Anees
Jun 29 at 10:30

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Opening a url is failing in Swift

Export result set on Dbeaver to CSV