python - Pandas 根据特殊要求拆分一列

标签 python pandas rows

我有一个喜欢下面的示例数据。 开始 在列中配对。

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

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

最佳答案

如果 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

关于python - Pandas 根据特殊要求拆分一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60612955/

相关文章:

python - 如何在 Python 中读取 SPSS aka (.sav)

python - Pandas fillna() 按特定顺序排列

python - 即使在使用 .loc 之后,也会尝试在来自 DataFrame 警告的切片副本上设置值

php - 使用 jQuery 按行和列插入值

python - 如何查询并从函数中获取最大值

python - 无法在 Python 中设置 __main__.__loader__

python - KivyMD 如何更改 MDToolbar 标题大小和字体?

python - 将附加参数传递给 python 回调对象 (win32com.client.dispatchWithEvents)

php - MySQL JOIN 一个表的多行到另一个表的一行

python - Numpy - 将行添加到数组