如何聚合文本文件的出现,然后将其绘制到Python中

2024-06-16 15:06:41 发布

您现在位置: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

因此,我想将数据帧分离为单独的数据帧,其中每个数据帧将由文本列中列表中每个ticker的出现组成。 这是我试过的

check = discussion[discussion['text'].map(lambda txt: any(tag in txt for tag in top))]

我得到了正确的输出,现在我想用列表中的某个标记器绘制行的每个匹配项 我希望我的x轴是日期,y轴是股票代码。换句话说,我想有4个独立的图,每个图都是独立的代码

谢谢你的帮助


Tags: csvto数据textintxt列表my
4条回答

对所有匹配值使用^{},对单词边界使用\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

对于计数使用^{}

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

^{}进行的最后绘图:

df1.plot()

this解决方案编辑:

import matplotlib.pyplot as plt

for col in df1.columns:
    df1[col].plot()
    plt.show()

相关问题 更多 >