'Adding new column as a sum of the subsquent columns [duplicate]

I have this df:

id   car  truck  bus  bike
0     1     1     0    0
1     0     0     1    0
2     1     1     1    1

I want to add another column count to this df but after id and before car to sum the values of the rows, like this:

id  count car  truck  bus  bike
0     2     1     1     0    0
1     1     0     0     1    0
2     4     1     1     1    1

I know how to add the column using this code:

df.loc[:,'count'] = df.sum(numeric_only=True, axis=1)

but the above code add the new column in the last position.

How can I fix this?



Solution 1:[1]

try this slight modification of your code:

import pandas as pd
df = pd.DataFrame(data={'id':[0,1,2],'car':[1,0,1],'truck':[1,0,1],'bus':[0,1,1],'bike':[0,0,1]})
count = df.drop(columns=['id'],axis=1).sum(numeric_only=True, axis=1)
df.insert(1, "count", count)
print(df)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 prahasanam_boi