另一种选择,前提是您的数据帧
data = {
'symbol': [1712, 1726, 1824, 1871, 1887, 1871, 1887, 1871, 1887],
'weight': [0.007871, 0.00765, 0.032955, 0.006443, 0.00784, 0.006443, 0.00784, 0.006443, 0.00784],
'lqdty': [7.023737, 3.221021, 3.475508, 4.615002, 6.678486, 4.615002, 6.678486, 4.615002, 6.678486],
'date': [20210104, 20210104, 20210104, 20210105, 20210105, 20210105, 20210105, 20210106, 20210106]
}
index = [0, 1, 2, 0, 1, 2, 3, 0, 1]
df = pd.DataFrame(data, index=index)
会是
groups = pd.Series(df.index).eq(0).cumsum().values
result = pd.concat((sdf for _, sdf in df.groupby(groups)), axis=1)
结果:
symbol weight lqdty date symbol weight lqdty \
0 1712.0 0.007871 7.023737 20210104.0 1871 0.006443 4.615002
1 1726.0 0.007650 3.221021 20210104.0 1887 0.007840 6.678486
2 1824.0 0.032955 3.475508 20210104.0 1871 0.006443 4.615002
3 NaN NaN NaN NaN 1887 0.007840 6.678486
date symbol weight lqdty date
0 20210105 1871.0 0.006443 4.615002 20210106.0
1 20210105 1887.0 0.007840 6.678486 20210106.0
2 20210105 NaN NaN NaN NaN
3 20210105 NaN NaN NaN NaN