python - 如何聚合文本文件的出现然后绘制它Python
问题描述
我有一个清单
top = ['GME', 'MVIS', 'TSLA', 'AMC']
我有一个数据集
discussion = pd.read_csv('discussion_thread_data.csv')
dt | text
2021-03-19 20:59:49+06 | I only need GME to hit 20 eod to make up
2021-03-19 20:59:51+06 | lads why is my account covered in more red
2021-05-21 15:54:27+06 | Oh my god, we might have 2 green days in a row
2021-05-21 15:56:06+06 | Why are people so hype about a 4% TSLA move
因此,我想将数据框分成单独的数据框,其中每个数据框将包含文本列中列表中每个股票代码的出现。这是我尝试过的
check = discussion[discussion['text'].map(lambda txt: any(tag in txt for tag in top))]
我得到了正确的输出,现在我想用列表中的某个代码来绘制行的每个出现,我希望我的 x 轴是日期,y 轴是代码。换句话说,我想要 4 个单独的图表,每个图表都是单独的代码。
感谢任何帮助
解决方案
使用for 单词边界Series.str.extractall
的所有匹配值:\b\b
top = ['GME', 'MVIS', 'TSLA', 'AMC']
pat = '|'.join(r"\b{}\b".format(x) for x in top)
df = discussion.set_index('dt')['text'].str.extractall('('+pat+')')[0].reset_index(name='v')
print (df)
dt match v
0 2021-03-19 20:59:49+06 0 GME
1 2021-05-21 15:56:06+06 0 TSLA
计数使用crosstab
:
df1 = pd.crosstab(df['dt'], df['v'])
print (df1)
val GME TSLA
dt
2021-03-19 20:59:49+06 1 0
2021-05-21 15:56:06+06 0 1
最后绘制者DataFrame.plot
:
df1.plot()
通过此解决方案编辑:
import matplotlib.pyplot as plt
for col in df1.columns:
df1[col].plot()
plt.show()
推荐阅读
- vue.js - Vuetify - 仅包含使用过的组件和 css
- excel - 为什么使用 VBA 时会自动填充一列?
- python-3.x - pysnmpget ,pysnmp.smi.error.SmiError: 没有符号 IF-MIB::ifDescr.1 at
- mysql - 如何使用组和多个连接进行查询
- sql-server - 是否有一种方便的方法可以根据源表的更改(重新)创建表?
- php - 将 MongoDB 与 Symfony 5.2 连接时出错
- r - plotly::add_annotations() 无法处理因子变量(?)
- python - 沿着列表选择具有恒定距离的点,python
- html - 渐进式 Web 应用程序的 Apple 启动画面不显示
- weblogic - WebLogic 与 ActiveDirectory 的集成