如何将单列切割为二维pandas DataFrame?
我有多个仪器的单列时间序列数据:
DATE ISIN ASK 01.05.2017 XS1431271250 0.2401 02.03.2017 XS1431271250 0.2578 01.03.2017 XS1431271250 0.2665 01.05.2017 XS1431274601 0.0474 02.03.2017 XS1431274601 0.0471 01.03.2017 XS1431274601 0.0479 01.05.2017 XS1431271094 0.2419 02.03.2017 XS1431271094 0.2454 01.03.2017 XS1431271094 0.254
而不是它我需要每个ISIN的单列:
Date XS1431271250 XS1431274601 XS1431271094 01.05.2017 0.2401 0.0474 0.2419 02.03.2017 0.2578 0.0471 0.2454 01.03.2017 0.2665 0.0479 0.254
我尝试过分组,df.factorize,df.melt,但没有成功。 请以正确的方式提出建议?
答案 0 :(得分:0)
result = df.pivot('DATE','ISIN')
# ASK
#ISIN XS1431271094 XS1431271250 XS1431274601
#DATE
#01.03.2017 0.2540 0.2665 0.0479
#01.05.2017 0.2419 0.2401 0.0474
#02.03.2017 0.2454 0.2578 0.0471
如果您更喜欢扁平列名称,则可以删除' ASK'电平:
result.columns = result.columns.get_level_values(1)
#ISIN XS1431271094 XS1431271250 XS1431274601
#DATE
#01.03.2017 0.2540 0.2665 0.0479
#01.05.2017 0.2419 0.2401 0.0474
#02.03.2017 0.2454 0.2578 0.0471
答案 1 :(得分:0)
此操作称为pivot
:
>>> df.pivot(index='DATE', columns='ISIN')
ASK
ISIN XS1431271094 XS1431271250 XS1431274601
DATE
01.03.2017 0.2540 0.2665 0.0479
01.05.2017 0.2419 0.2401 0.0474
02.03.2017 0.2454 0.2578 0.0471
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html