将多列中的行移动到它们自己的列中 Python

Bys*_*108 2 python dataframe pandas

我有一个关于购买数据的数据框,我需要移动它以使其易于分析。到目前为止它看起来像:

'''

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
Run Code Online (Sandbox Code Playgroud)

在上面的示例表中,索引 2 和 6 中的行表示有关其上方记录的特定项目数据,因此我需要它们从当前列中拉出并移至其相关记录旁边的自己的列。所以我理想情况下需要数据框看起来像这样:

'''

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
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 6

如果数据的第一个数字行被一个非数字行按price列拆分,则解决方案有效:

#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
Run Code Online (Sandbox Code Playgroud)