从没有 for 循环的整洁数据创建价格矩阵

数据挖掘 Python 熊猫
2022-03-02 14:35:22

我有以下格式的数据框

     symbol     name        date   close      market
0    BTC  Bitcoin  2013-04-28  134.21  1500520000
1    BTC  Bitcoin  2013-04-29  144.54  1491160000
2    BTC  Bitcoin  2013-04-30  139.00  1597780000
3    BTC  Bitcoin  2013-05-01  116.99  1542820000
4    BTC  Bitcoin  2013-05-02  105.21  1292190000
...
          symbol    name        date     close  market
752109    W3C  W3Coin  2018-04-07  0.000277       0
752110    W3C  W3Coin  2018-04-08  0.000286       0
752111    W3C  W3Coin  2018-04-09  0.000270       0
752112    W3C  W3Coin  2018-04-10  0.000286       0
752113    W3C  W3Coin  2018-04-11  0.000300       0

我想创建一个包含价格的矩阵和一个包含市值的矩阵。因为我对重新创建 S&P500 指数感兴趣。我已经用下面的 for 循环完成了这个。问题:如果没有 for 循环,我该如何做到这一点?

编辑:请注意,某些符号的日期数不同,例如 BTC 可能有 1000 天,但 W3Coin 只有 50 天。我认为这就是错误消息告诉我的内容。

导入数据:

df = pd.read_csv('data-coins-scrape/CryptoData.csv', parse_dates=True)
cols = ['symbol', 'name', 'date', 'close', 'market']
df = df[cols]
symbols = df.symbol.unique()
nr_coins = df.symbol.nunique()

for 循环获取价格和 makretcaps

prices = []
marketscaps = []
shapes = []
for s in symbols:
    # slice out one coin
    dfc = df.loc[df.symbol == s]
    shapes.append(dfc.shape)
    prices.append(dfc['close'])
    marketcaps.append(df['market'])
del dfc

检查输出

len(prices), len(marketcaps) 
# (1531, 3065) is the output 

type(prices[0]), prices[0].shape, prices[0].name 
# output: (pandas.core.series.Series, (1810,), 'close')

df.loc[df.symbol == 'BTC', 'close'].head() == prices[0].head() 
# returns True 
2个回答

您可以执行以下操作:

df1 = df.set_index(['name', 'date'])
prices = df1['close'].unstack()
marketcaps = df1['marketcaps'].unstack()

用 pd.concat 创建一个价格矩阵,有些可行,有些给出类型错误

pd.concat([prices[0], prices[1], prices[2], prices[3]], axis=1, join='outer').tail() 
# works!

pricemat = pd.concat(prices, keys=[btc.index], axis=1) 
# TypeError: unhashable type: 'DatetimeIndex'

pricemat = pd.concat(prices, axis=1) 
#TypeError: unhashable type: 'DatetimeIndex'

使用 for 循环创建价格矩阵,给出值错误:

priced_df = prices[0]
K = len(prices)
for i in range(1, K):
    priced_df = pd.concat([priced_df, prices[i]], axis=1)
    print(priced_df.shape[1])
# at 25 it stops and says:

# ValueError: Shape of passed values is (25, 2057), indices imply (25, 1810)