-1

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?

pouchewar
  • 399
  • 1
  • 10
  • You can refer this question for details about column reordering in dataframe https://stackoverflow.com/questions/13148429/how-to-change-the-order-of-dataframe-columns – Manjunath K Mayya Feb 26 '22 at 04:26

2 Answers2

2

There are several ways. I provided two ways here.

#1. Changing column order after creating count column:

df.loc[:,'count'] = df.sum(numeric_only=True, axis=1)
df.columns = ['id', 'count', 'car', 'truck', 'bus', 'bike']
print(df)
#   id  count  car  truck  bus  bike
#0   0      2    1      1    0     0
#1   1      2    0      0    1     0
#2   2      6    1      1    1     1

#2. Inserting a Series to specific position using insert function:

df.insert(1, "count", df.sum(numeric_only=True, axis=1))
print(df)
#   id  count  car  truck  bus  bike
#0   0      2    1      1    0     0
#1   1      2    0      0    1     0
#2   2      6    1      1    1     1
Park
  • 2,446
  • 1
  • 16
  • 25
0

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)
prahasanam_boi
  • 816
  • 3
  • 10