简体   繁体   中英

Insert total rows in a table, without using Pandas but using only loops

I have a table like this -

     Cell Sales Lag
0    -8    1    
1    -8    3    1
2    -8    2    3
3    -7    9    
4    -7    3    9

I want to insert a Total row that takes the last value of "Sales" column for each cell group and insert it in the "Sales" column, and takes the first value of the "Sales" column for a cell group and inserts it in the lag column.

The result should look like -

     Cell Sales Lag
0    -8    1    
1    -8    3    1
2    -8    2    3
3    Total 2    1
4    -7    9    
5    -7    3    9
6    Total 3    9

I am sorry I am not able to come up with any logic to solve this. Please be kind.

Do keep in mind the inserting rows in a dataframe is highly inefficient. Here is how I will go about it:

import pandas as pd
from io import StringIO

ss = StringIO('''
Index  Cell Sales Lag
0    -8    1    
1    -8    3    1
2    -8    2    3
3    -7    9    
4    -7    3    9
''')

df = pd.read_csv(ss, sep='\s+')
del df['Index']


# Store the firsts
df_first = df.groupby('Cell')['Sales'].first()

# Store the lasts
df_last = df.groupby('Cell')['Sales'].last()

df_new = pd.DataFrame(columns=df.columns)
for row in df_first.index:
    df_temp = df[df.Cell == row]
    df_new = df_new.append(df_temp, ignore_index=True)

    df_insert = pd.DataFrame({df.columns[0]:'Total', 
                             df.columns[1]:df_last.loc[df_last.index==row],
                             df.columns[2]:df_first.loc[df_first.index==row]})
    df_new = df_new.append(df_insert)

It generates the desired output:

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM