404 KiB
404 KiB
In [6]:
# load in data
import pandas as pd
from pathlib import Path
tweet_df = pd.read_csv('tweets_relevance_list.csv', index_col=0)
# remove rows with score of zero
tweet_df = tweet_df[tweet_df['score'].gt(0)]
# remove wrong folder
tweet_df['path'] = tweet_df['path'].str.replace('/home/brian/solveig_master/', '')
# ensure datatype
tweet_df['path'] = tweet_df['path'].apply(Path)
tweet_dfOut [6]:
| path | score | |
|---|---|---|
| 0 | tweets/2021-08-24-07-40.txt | 15 |
| 1 | tweets/2021-06-22-13-19.txt | 14 |
| 2 | tweets/2020-07-13-10-03.txt | 14 |
| 3 | tweets/2022-04-28-12-38.txt | 13 |
| 4 | tweets/2022-10-20-14-08.txt | 13 |
| ... | ... | ... |
| 1331 | tweets/2016-11-08-13-35.txt | 1 |
| 1332 | tweets/2022-06-16-12-15.txt | 1 |
| 1333 | tweets/2016-05-12-12-48.txt | 1 |
| 1334 | tweets/2016-06-01-11-03.txt | 1 |
| 1335 | tweets/2014-01-28-08-50.txt | 1 |
1336 rows × 2 columns
In [7]:
# define time bins
period_range = pd.period_range(start='2011-01-01', end='2023-03-31', freq='M')
period_rangeOut [7]:
PeriodIndex(['2011-01', '2011-02', '2011-03', '2011-04', '2011-05', '2011-06',
'2011-07', '2011-08', '2011-09', '2011-10',
...
'2022-06', '2022-07', '2022-08', '2022-09', '2022-10', '2022-11',
'2022-12', '2023-01', '2023-02', '2023-03'],
dtype='period[M]', length=147)In [8]:
# prepare dataframe
df = pd.DataFrame(index=period_range, columns=['count', 'total'])
df.iloc[:, :] = 0 # set all to 0
dfOut [8]:
| count | total | |
|---|---|---|
| 2011-01 | 0 | 0 |
| 2011-02 | 0 | 0 |
| 2011-03 | 0 | 0 |
| 2011-04 | 0 | 0 |
| 2011-05 | 0 | 0 |
| ... | ... | ... |
| 2022-11 | 0 | 0 |
| 2022-12 | 0 | 0 |
| 2023-01 | 0 | 0 |
| 2023-02 | 0 | 0 |
| 2023-03 | 0 | 0 |
147 rows × 2 columns
In [9]:
# count words usage
from datetime import datetime
for path in tweet_df['path']:
# determine period
ts = datetime.strptime(path.stem, '%Y-%m-%d-%H-%M')
ts = pd.to_datetime(ts).to_period('M')
# increase count
df.loc[ts, 'count'] += 1
dfOut [9]:
| count | total | |
|---|---|---|
| 2011-01 | 0 | 0 |
| 2011-02 | 0 | 0 |
| 2011-03 | 0 | 0 |
| 2011-04 | 0 | 0 |
| 2011-05 | 0 | 0 |
| ... | ... | ... |
| 2022-11 | 23 | 0 |
| 2022-12 | 29 | 0 |
| 2023-01 | 19 | 0 |
| 2023-02 | 20 | 0 |
| 2023-03 | 15 | 0 |
147 rows × 2 columns
In [5]:
from database import connect as connect_db
db = connect_db()
# load in all tweet dates
cursor = db.find({'account': '@Maersk'})
time_list = list()
for element in cursor:
try:
time_list.append(element['time'])
except:
print(f"failed getting {element['_id']}")
print(f'got {len(time_list)} tweets')
with open('tweet_time_list.txt', 'w') as fh:
fh.write('\n'.join(time_list))[0;31m---------------------------------------------------------------------------[0m [0;31mKeyboardInterrupt[0m Traceback (most recent call last) Cell [0;32mIn[5], line 8[0m [1;32m 6[0m cursor [39m=[39m db[39m.[39mfind({[39m'[39m[39maccount[39m[39m'[39m: [39m'[39m[39m@Maersk[39m[39m'[39m}) [1;32m 7[0m time_list [39m=[39m [39mlist[39m() [0;32m----> 8[0m [39mfor[39;00m element [39min[39;00m cursor: [1;32m 9[0m [39mtry[39;00m: [1;32m 10[0m time_list[39m.[39mappend(element[[39m'[39m[39mtime[39m[39m'[39m]) File [0;32m~/Desktop/solveig_master/venv/lib/python3.8/site-packages/pymongo/cursor.py:1248[0m, in [0;36mCursor.next[0;34m(self)[0m [1;32m 1246[0m [39mif[39;00m [39mself[39m[39m.[39m__empty: [1;32m 1247[0m [39mraise[39;00m [39mStopIteration[39;00m [0;32m-> 1248[0m [39mif[39;00m [39mlen[39m([39mself[39m[39m.[39m__data) [39mor[39;00m [39mself[39;49m[39m.[39;49m_refresh(): [1;32m 1249[0m [39mreturn[39;00m [39mself[39m[39m.[39m__data[39m.[39mpopleft() [1;32m 1250[0m [39melse[39;00m: File [0;32m~/Desktop/solveig_master/venv/lib/python3.8/site-packages/pymongo/cursor.py:1139[0m, in [0;36mCursor._refresh[0;34m(self)[0m [1;32m 1136[0m [39mreturn[39;00m [39mlen[39m([39mself[39m[39m.[39m__data) [1;32m 1138[0m [39mif[39;00m [39mnot[39;00m [39mself[39m[39m.[39m__session: [0;32m-> 1139[0m [39mself[39m[39m.[39m__session [39m=[39m [39mself[39;49m[39m.[39;49m__collection[39m.[39;49mdatabase[39m.[39;49mclient[39m.[39;49m_ensure_session() [1;32m 1141[0m [39mif[39;00m [39mself[39m[39m.[39m__id [39mis[39;00m [39mNone[39;00m: [39m# Query[39;00m [1;32m 1142[0m [39mif[39;00m ([39mself[39m[39m.[39m__min [39mor[39;00m [39mself[39m[39m.[39m__max) [39mand[39;00m [39mnot[39;00m [39mself[39m[39m.[39m__hint: File [0;32m~/Desktop/solveig_master/venv/lib/python3.8/site-packages/pymongo/mongo_client.py:1740[0m, in [0;36mMongoClient._ensure_session[0;34m(self, session)[0m [1;32m 1735[0m [39mreturn[39;00m session [1;32m 1737[0m [39mtry[39;00m: [1;32m 1738[0m [39m# Don't make implicit sessions causally consistent. Applications[39;00m [1;32m 1739[0m [39m# should always opt-in.[39;00m [0;32m-> 1740[0m [39mreturn[39;00m [39mself[39;49m[39m.[39;49m__start_session([39mTrue[39;49;00m, causal_consistency[39m=[39;49m[39mFalse[39;49;00m) [1;32m 1741[0m [39mexcept[39;00m (ConfigurationError, InvalidOperation): [1;32m 1742[0m [39m# Sessions not supported.[39;00m [1;32m 1743[0m [39mreturn[39;00m [39mNone[39;00m File [0;32m~/Desktop/solveig_master/venv/lib/python3.8/site-packages/pymongo/mongo_client.py:1685[0m, in [0;36mMongoClient.__start_session[0;34m(self, implicit, **kwargs)[0m [1;32m 1682[0m [39mdef[39;00m [39m__start_session[39m([39mself[39m, implicit, [39m*[39m[39m*[39mkwargs): [1;32m 1683[0m [39m# Raises ConfigurationError if sessions are not supported.[39;00m [1;32m 1684[0m [39mif[39;00m implicit: [0;32m-> 1685[0m [39mself[39;49m[39m.[39;49m_topology[39m.[39;49m_check_implicit_session_support() [1;32m 1686[0m server_session [39m=[39m _EmptyServerSession() [1;32m 1687[0m [39melse[39;00m: File [0;32m~/Desktop/solveig_master/venv/lib/python3.8/site-packages/pymongo/topology.py:538[0m, in [0;36mTopology._check_implicit_session_support[0;34m(self)[0m [1;32m 536[0m [39mdef[39;00m [39m_check_implicit_session_support[39m([39mself[39m): [1;32m 537[0m [39mwith[39;00m [39mself[39m[39m.[39m_lock: [0;32m--> 538[0m [39mself[39;49m[39m.[39;49m_check_session_support() File [0;32m~/Desktop/solveig_master/venv/lib/python3.8/site-packages/pymongo/topology.py:554[0m, in [0;36mTopology._check_session_support[0;34m(self)[0m [1;32m 550[0m [39mself[39m[39m.[39m_select_servers_loop( [1;32m 551[0m any_server_selector, [39mself[39m[39m.[39mget_server_selection_timeout(), [39mNone[39;00m [1;32m 552[0m ) [1;32m 553[0m [39melif[39;00m [39mnot[39;00m [39mself[39m[39m.[39m_description[39m.[39mreadable_servers: [0;32m--> 554[0m [39mself[39;49m[39m.[39;49m_select_servers_loop( [1;32m 555[0m readable_server_selector, [39mself[39;49m[39m.[39;49mget_server_selection_timeout(), [39mNone[39;49;00m [1;32m 556[0m ) [1;32m 558[0m session_timeout [39m=[39m [39mself[39m[39m.[39m_description[39m.[39mlogical_session_timeout_minutes [1;32m 559[0m [39mif[39;00m session_timeout [39mis[39;00m [39mNone[39;00m: File [0;32m~/Desktop/solveig_master/venv/lib/python3.8/site-packages/pymongo/topology.py:250[0m, in [0;36mTopology._select_servers_loop[0;34m(self, selector, timeout, address)[0m [1;32m 244[0m [39mself[39m[39m.[39m_request_check_all() [1;32m 246[0m [39m# Release the lock and wait for the topology description to[39;00m [1;32m 247[0m [39m# change, or for a timeout. We won't miss any changes that[39;00m [1;32m 248[0m [39m# came after our most recent apply_selector call, since we've[39;00m [1;32m 249[0m [39m# held the lock until now.[39;00m [0;32m--> 250[0m [39mself[39;49m[39m.[39;49m_condition[39m.[39;49mwait(common[39m.[39;49mMIN_HEARTBEAT_INTERVAL) [1;32m 251[0m [39mself[39m[39m.[39m_description[39m.[39mcheck_compatible() [1;32m 252[0m now [39m=[39m time[39m.[39mmonotonic() File [0;32m/usr/local/opt/[email protected]/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py:306[0m, in [0;36mCondition.wait[0;34m(self, timeout)[0m [1;32m 304[0m [39melse[39;00m: [1;32m 305[0m [39mif[39;00m timeout [39m>[39m [39m0[39m: [0;32m--> 306[0m gotit [39m=[39m waiter[39m.[39;49macquire([39mTrue[39;49;00m, timeout) [1;32m 307[0m [39melse[39;00m: [1;32m 308[0m gotit [39m=[39m waiter[39m.[39macquire([39mFalse[39;00m) [0;31mKeyboardInterrupt[0m:
In [10]:
# load in time list
with open('tweet_time_list.txt', 'r') as fh:
content = fh.read()
time_list = content.split('\n')
time_list[:5]Out [10]:
['2023-03-12 10:02:05', '2023-03-13 12:05:06', '2023-03-10 12:24:49', '2023-03-08 08:43:44', '2023-03-15 11:10:19']
In [11]:
# count total tweets
from datetime import datetime
for time_str in time_list:
# determine period
ts = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
ts = pd.to_datetime(ts).to_period('M')
# increase count
df.loc[ts, 'total'] += 1
dfOut [11]:
| count | total | |
|---|---|---|
| 2011-01 | 0 | 0 |
| 2011-02 | 0 | 0 |
| 2011-03 | 0 | 0 |
| 2011-04 | 0 | 0 |
| 2011-05 | 0 | 0 |
| ... | ... | ... |
| 2022-11 | 23 | 57 |
| 2022-12 | 29 | 65 |
| 2023-01 | 19 | 51 |
| 2023-02 | 20 | 63 |
| 2023-03 | 15 | 32 |
147 rows × 2 columns
In [12]:
# calculate ratio
df['ratio'] = 0
above_zero_mask = df['total'].gt(0)
df.loc[above_zero_mask, 'ratio'] = df.loc[above_zero_mask, 'count'] / df.loc[above_zero_mask, 'total']
dfOut [12]:
| count | total | ratio | |
|---|---|---|---|
| 2011-01 | 0 | 0 | 0 |
| 2011-02 | 0 | 0 | 0 |
| 2011-03 | 0 | 0 | 0 |
| 2011-04 | 0 | 0 | 0 |
| 2011-05 | 0 | 0 | 0 |
| ... | ... | ... | ... |
| 2022-11 | 23 | 57 | 0.403509 |
| 2022-12 | 29 | 65 | 0.446154 |
| 2023-01 | 19 | 51 | 0.372549 |
| 2023-02 | 20 | 63 | 0.31746 |
| 2023-03 | 15 | 32 | 0.46875 |
147 rows × 3 columns
In [13]:
# plot of combined use of root words over time
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import seaborn as sns
%matplotlib widget
plt.figure(figsize=(12,8))
time = df.index.to_timestamp()
counts = df['ratio'] * 100
plt.plot(time, counts, label='sustainability-related tweets')
mean = counts.rolling(12, min_periods=1).mean()
plt.plot(time, mean, label='12-month mean')
std = counts.rolling(12, min_periods=1).std()
plt.fill_between(
x=time,
y1=mean-std,
y2=mean+std,
alpha=0.2,
label='12-month standard deviation'
)
locator = mdates.MonthLocator(interval=12)
fmt = mdates.DateFormatter('%Y-%m')
x_axis = plt.gca().xaxis
x_axis.set_major_locator(locator)
x_axis.set_major_formatter(fmt)
plt.xticks(rotation=45)
plt.ylabel('percent of total tweets (%)')
plt.legend(loc='upper left')
plt.tight_layout()
sns.despine(left=True)
sns.set_style("ticks",{'axes.grid' : True})
plt.savefig('plots/total_tweet_ratio.png')
plt.show()In [ ]: