【发布时间】:2019-07-30 23:07:36
【问题描述】:
我创建了一个数据框,其中包含 10 年每个月末的 300 只股票的十几个属性(例如市盈率、市盈率)。数据框最初按月份索引(因此每个月有 300 个观察值),然后按股票代码(因此每个代码有 400 个观察值)。我的数据框有大约 12 列和 120,000 行。
我现在想转置数据框,使这些列成为股票代码,即大约有 300 列,每只股票一个。我希望日期继续与每一行相关联,这样我就有大约 4,800 行与一列中的每个代码相关联(12 个变量 x 400 个观察值)。
#Sort the dataframe, first by ticker and then by date, then write to Excel
DF.sort_values(by=['Date', 'ticker'], inplace=True)
DF.to_excel(outPath + outFn1)
#Now make ticker the index and sort by ticker and date
DF = DF.reset_index().set_index('ticker')
DF.sort_values(by=['ticker', 'Date'], inplace=True)
DF.to_excel(outPath + outFn2)
#Now transpose the dataframe
DF = DF.reset_index().set_index('Date')
DF = DF.transpose()
DF.to_excel(outPath + outFn3)
不幸的是,当我执行最后一个 df.transpose() 时,我得到了 120,000 列和只有 12 行 - 300 个股票代码和 400 个月份被转换为 120,000 个列,月份(索引)显示在第一行!有没有办法只有 300 列(每个股票一个)和 4,800 行(每个变量每个月一个)?
非常感谢您的帮助
托马斯·飞利浦
【问题讨论】:
-
你能给我们看一个数据的例子吗?
-
日期cusip ticker bp pm12m1m 1986-12-31 00:00:00 037833100 aapl 0.8181818 1987-01-31 0.8181818 1987-01-31 0.8181818 1987-01-31 0.811818 1987-01-31 00:00:00 037833100 AAAPL 0.1996882 0.7513514 1987-02-28 00:00:00: 00 037833100 AAPL 0.158324 1.22
-
日期cusip ticker bp pm12m1m 1986-12-31 00:00:00 037833100 aapl 0.8181818 1987-01-31 0.8181818 1987-01-31 0.8181818 1987-01-31 0.811818 1987-01-31 00:00:00 037833100 AAAPL 0.1996882 0.7513514 1987-02-28 00:00:00: 00 037833100 AAPL 0.158324 1.22
标签: pandas dataframe transpose