我有两个数据集。
market 变量中的第一个包含具有以下结构的通用市场趋势:
Date High Close Volume Open Low
第二个,在 moods 变量中,每天包含一些在此结构中具有关联情绪的推文:
body date datetime id sentiment time
所以,我想计算每天有多少“看跌”和“看涨”情绪。它有效,这是我的带有注释的代码:
# Read the datasets
market = pd.read_csv("Datasets/SP500/aggregates.txt")
moods = pd.read_json("Datasets/DatasetStockTwits-Aggregato.json")
# Remove all null sentiments
moods = moods[moods.sentiment != "null"]
# Get a generic subsets of data for computational speed
market_tail = market.tail(100)
# For each day present in market_tail, get the same days twits
moods_tail = moods.loc[moods['date'].isin(market_tail.Date)]
# So now I count for each day how many "Bearish" and "Bullish" twits there are
sentiments_count = pd.crosstab(moods_tail['date'], moods_tail['sentiment'])
print(sentiments_count)
这是结果:
sentiment Bearish Bullish
date
2017-11-03 9 12
2017-11-05 3 6
2017-11-06 20 9
2017-11-07 16 35
所以它工作正常,但我不明白为什么我无法访问 sentiments_count.date
或sentiments_count['date']
索引。
事实上,如果我尝试这样的事情:
print(sentiments_count['date'])
我得到:KeyError: 'date'
我错过了什么吗? 谢谢
最佳答案
不能选择它,因为它是index
,所以需要:
print(sentiments_count.index)
要从索引
创建列,需要 reset_index
,也可以添加 rename_axis
进行数据清理用于删除列名称sentiment
:
sentiments_count = sentiments_count.reset_index().rename_axis(None, 1)
print(sentiments_count['date'])
关于python - 索引使用 CrossTab Pandas 获得的 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53225248/