我的实验室仪器提供了如下格式的数据集。对于上下文,我只有很少的python经验。
<表类>
TTS
周期1
tbody><<tr>波长(nm) 吸光度 100 12 200 23 300 17 400 14 TTS 循环2 波长(nm) 吸光度 100 73 200 25 300 179 400 15 TTS 周期3 波长(nm) 吸光度 100 60 200 45 300 12 400 100 表类>
首先在read_csv
中创建默认为0,1
列的DataFrame,header=None
参数:
df = pd.read_csv(file, header=None)
print (df)
0 1
0 TTS Cycle 1
1 Wavelength (nm) Absorbance
2 100 12
3 200 23
4 300 17
5 400 14
6 TTS Cycle 2
7 Wavelength (nm) Absorbance
8 100 73
9 200 25
10 300 179
11 400 15
12 TTS Cycle 3
13 Wavelength (nm) Absorbance
14 100 60
15 200 45
16 300 12
17 400 100
然后为识别循环创建组,这里通过TTS
比较第一列,并将第二列的值重复到c
列,并通过GroupBy.cumcount
创建g
组,因此可能进行pivot并在列表推导中创建最终列名:
m = df[0].eq('TTS')
df1 = (df[~m & df[1].ne('Absorbance')]
.assign(c=df[1].where(m).ffill().fillna(df.columns[1]),
g=lambda x: x.groupby('c').cumcount()).pivot(index='g', columns='c')
.sort_index(level=1, axis=1)
.rename(columns={0:'Wavelength', 1:'Absorbance'}))
df1.columns = [f'{a} ({b})' for a, b in df1.columns]
print (df1)
Wavelength (Cycle 1) Absorbance (Cycle 1) Wavelength (Cycle 2)
g
0 100 12 100
1 200 23 200
2 300 17 300
3 400 14 400
Absorbance (Cycle 2) Wavelength (Cycle 3) Absorbance (Cycle 3)
g
0 73 100 60
1 25 200 45
2 179 300 12
3 15 400 100
如果每个周期的波长相同,可以创建一个列:
m = df[0].eq('TTS')
df2 = (df[~m & df[1].ne('Absorbance')]
.assign(c=df[1].where(m).ffill().fillna(df.columns[1]),
g=lambda x: x.groupby('c').cumcount()).pivot(index=0, columns='c', values=1)
.rename_axis(index='Wavelength', columns=None)
.rename(columns= lambda x: f'Absorbance ({x})')
.reset_index()
)
print (df2)
Wavelength Absorbance (Cycle 1) Absorbance (Cycle 2) Absorbance (Cycle 3)
0 100 12 73 60
1 200 23 25 45
2 300 17 179 12
3 400 14 15 100