熊猫根据特殊要求拆分了一列

问题描述 投票:4回答:1

我有一个示例数据,如下所示。 StartEnd在该列中配对。

而且我不知道一个开始和结束之间有多少行,因为实际数据很大。

df = pd.DataFrame({'Item':['Item_A','<Start>','A1','A2','<End>','Item_B','<Start>','B1','B2','B3','<End>']})

print (df)
       Item
0    Item_A
1   <Start>
2        A1
3        A2
4     <End>
5    Item_B
6   <Start>
7        B1
8        B2
9        B3
10    <End>

如何使用Pandas将其更改为以下格式?谢谢。

enter image description here

python pandas rows
1个回答
0
投票

如果Item值比Start行高一行,则解决方案有效:

#compare for Start
m1 = df['Item'].eq('<Start>')
#get Item rows by shift Start mask
m2 = m1.shift(-1, fill_value=False)
#replace non Item values to missing values and forward filling them
df['new'] = df['Item'].where(m2).ffill()
#compare End
m3 = df['Item'].eq('<End>')

#filter no matched rows between Start and End to m4
g = m1.cumsum()
s = m3.shift().cumsum()
m4 = s.groupby(g).transform('min').ne(s)

#filtering with swap columns
df1 = df.loc[~(m4 | m1 | m3), ['new','Item']].copy()
#new columns names
df1.columns = ['Item','Detail']
#replace duplicated to empty string
df1['Item'] = np.where(df1['Item'].duplicated(), '', df1['Item'])
print (df1)
     Item Detail
2  Item_A     A1
3             A2
7  Item_B     B1
8             B2
9             B3
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.