Moving rows in multiple columns into their own columns Python

Bystrov_2108 :

I've got a dataframe about purchase data which i need to shift around to make it easy to analyse. So far it looks like:

'''

df = 

  | customers bid/offer price  volume
 0| 28        B         95     1200
 1| 1         O         78     6
 2| SOA       IFILL     May20  F
 3| 15        B         99     3
 4| 18        O         60     3
 5| 120       B         40     70
 6| FAL       TGAL      May20  F

In the example table above the rows in index 2 and 6 represent specific item data about the records above them so i need them to have pulled out of the current columns and move over to their own columns next their relevant records. So i need the dataframe ideally to looks like this:

'''

df =

 | customers bid/offer price volume shopCode itemCode date  Type
0| 28        B         95    1200   SOA      IFILL    May20 F
1| 1         O         78    6      SOA      IFILL    May20 F
2| 15        B         99    3      FAL      TGAL     May20 F
3| 18        O         60    3      FAL      TGAL     May20 F
4| 120       B         40    70     FAL      TGAL     May20 F
jezrael :

Solution working if data has first numeric rows splitted by one non numeric rows by price column:

#for correct default RangeIndex
df = df.reset_index(drop=True)

#test numeric rows
m = df['price'].str.isnumeric()
#join together with removed 1 from index for correct match
df1 = pd.concat([df[m], df[~m].rename(lambda x: x-1)], axis=1)
#set correct columns names
L = ['shopCode','itemCode','date','Type']
df1.columns = df.columns.tolist() + L
#back filling missing values
df1[L] = df1[L].bfill()
print (df1)
  customers bid/offer price volume shopCode itemCode   date Type
0        28         B    95   1200      SOA    IFILL  May20    F
1         1         O    78      6      SOA    IFILL  May20    F
3        15         B    99      3      FAL     TGAL  May20    F
4        18         O    60      3      FAL     TGAL  May20    F
5       120         B    40     70      FAL     TGAL  May20    F

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=301606&siteId=1