パンダを使用して、Twitter データセットから文字列マッチングを実行しています。
ツイートの CSV をインポートし、日付を使用してインデックスを作成しました。次に、一致するテキストを含む新しい列を作成しました。
In [1]:
import pandas as pd
indata = pd.read_csv('tweets.csv')
indata.index = pd.to_datetime(indata["Date"])
indata["matches"] = indata.Tweet.str.findall("rudd|abbott")
only_results = pd.Series(indata["matches"])
only_results.head(10)
Out[1]:
Date
2013-08-06 16:03:17 []
2013-08-06 16:03:12 []
2013-08-06 16:03:10 []
2013-08-06 16:03:09 []
2013-08-06 16:03:08 []
2013-08-06 16:03:07 []
2013-08-06 16:03:07 [abbott]
2013-08-06 16:03:06 []
2013-08-06 16:03:02 []
2013-08-06 16:03:00 [rudd]
Name: matches, dtype: object
私が最終的に望んでいるのは、日/月ごとにグループ化されたデータフレームであり、さまざまな検索用語を列としてプロットしてからプロットできます。
別の SO 回答 ( https://stackoverflow.com/a/16637607/2034487 )で完璧なソリューションのように見えるものに出会いましたが、このシリーズに適用しようとすると例外が発生します:
In [2]: only_results.apply(lambda x: pd.Series(1,index=x)).fillna(0)
Out [2]: Exception - Traceback (most recent call last)
...
Exception: Reindexing only valid with uniquely valued Index objects
データフレーム内の変更を適用して、groupby 条件を適用および再適用し、プロットを効率的に実行できるようにしたいと考えています。.apply() メソッドのしくみについてもっと知りたいです。
前もって感謝します。
成功した回答後に更新
問題は、私が見たことのない「一致」列の重複にありました。その列を反復して重複を削除し、上記のリンク先の @Jeff の元のソリューションを使用しました。これは成功し、結果のシリーズで .groupby() を実行して、毎日、毎時などの傾向を確認できるようになりました。結果のプロットの例を次に示します。
In [3]: successful_run = only_results.apply(lambda x: pd.Series(1,index=x)).fillna(0)
In [4]: successful_run.groupby([successful_run.index.day,successful_run.index.hour]).sum().plot()
Out [4]: <matplotlib.axes.AxesSubplot at 0x110b51650>