【问题标题】:How to aggregate the occurence of text file and then graph it Python如何聚合文本文件的出现然后绘制它Python
【发布时间】:2021-10-02 06:14:35
【问题描述】:

我有一个清单

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 个单独的图表,每个图表都是单独的代码。

感谢任何帮助

【问题讨论】:

  • 不清楚聚合发生是什么意思,您可以按股票代码和应用列表分组。类似 df.groupby('ticker')['date'].apply(list)

标签: python pandas aggregate


【解决方案1】:

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()

this 编辑解决方案:

import matplotlib.pyplot as plt

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

【讨论】:

  • y轴上是否出现了特定的股票代码?
  • @yanbiceps - 完全正确。
  • 你能解释一下 str.extractall('('+pat+')')[0] 是做什么的吗?
  • @yanbiceps - 它从text by top 列表中提取所有值
  • @yanbiceps - 如果一个单元格中有多个值topI only need GME to hit 20 eod to make up TSLA,则使用extractall 进行可能的提取
猜你喜欢
  • 1970-01-01
  • 2018-04-24
  • 1970-01-01
  • 2021-12-23
  • 2021-05-27
  • 2021-12-05
  • 1970-01-01
  • 2016-04-22
  • 1970-01-01
相关资源
最近更新 更多