我需要在出现“^”字符时将行中的项目拆分为列。 这需要通过 pandas 来完成,最好没有循环
我有
0 A^
3 206-1C
4 502-2B
5 506-0.5C
6 604-1B
7 907-2B
8 G.ELITE^
9 A201-1C
10 A202-1B
我想要
A^ | G.精英^ |
---|---|
206-1C | A201-1C。 |
502-2B。 | A202-1B |
506-0.5C | |
604-1B | |
907-2B。 |
test=rd.query('texts.str.contains("\^")', engine='python')
pivot
的方法:
# get column of interest
s = df.iloc[:, 0]
# identify strings ending in "^"
m = s.str.endswith('^')
# reshape
out = (s
.to_frame(name='value')
.assign(col=s.where(m).ffill(),
index=s.groupby(m.cumsum()).cumcount())[~m]
.pivot(index='index', columns='col', values='value')
)
输出:
col A^ G.ELITE^
index
1 206-1C A201-1C
2 502-2B A202-1B
3 506-0.5C NaN
4 604-1B NaN
5 907-2B NaN