Cla*_*oni 1 python series dataframe pandas
我有一个包含多个列的pandas DataFrame.我想要完成的是将两列的值组合/堆叠到一列中,将每列的值一行堆叠起来(不幸的是,此要求阻止我使用类似解的联合).其他剩余列的内容可以重复.非常感谢任何帮助
#Current DataFrame
print(df)
Stock Ticker Index Ticker Price Date
AAPL INDX 100 12/31/2018 8:57
GOOG RSL 123 12/31/2018 8:57
GM COMP 90 12/31/2018 8:57
MMM NIKK 340 12/31/2018 8:57
INVD EUR 30 12/31/2018 8:57
#Desired results
print(df2)
Stock and Bench Price Date
AAPL 100 12/31/2018 8:57
INDX 100 12/31/2018 8:57
GOOG 123 12/31/2018 8:57
RSL 123 12/31/2018 8:57
GM 90 12/31/2018 8:57
COMP 90 12/31/2018 8:57
MMM 340 12/31/2018 8:57
NIKK 340 12/31/2018 8:57
INVD 30 12/31/2018 8:57
EUR 30 12/31/2018 8:57
Run Code Online (Sandbox Code Playgroud)
您可以将价格和日期列设置为索引并堆叠股票和股票代码.最后一些使用reset_index清理.
df.set_index(['Date', 'Price'])[['Stock Ticker','Index Ticker']].stack()\
.reset_index(2,drop = True).reset_index(name = 'Stock and Bench')
Date Price Stock and Bench
0 12/31/2018 8:57 100 AAPL
1 12/31/2018 8:57 100 INDX
2 12/31/2018 8:57 123 GOOG
3 12/31/2018 8:57 123 RSL
4 12/31/2018 8:57 90 GM
5 12/31/2018 8:57 90 COMP
6 12/31/2018 8:57 340 MMM
7 12/31/2018 8:57 340 NIKK
8 12/31/2018 8:57 30 INVD
9 12/31/2018 8:57 30 EUR
Run Code Online (Sandbox Code Playgroud)