I am creating a bag of words from a text corpus and am trying to limit the size of my vocabulary because the program freezes when I try to convert my list to a pandas dataframe. I am using Counter to count the number occurrences of each word:
from collections import Counter
bow = []
# corpus is list of text samples where each text sample is a list of words with variable length
for tokenized_text in corpus:
clean_text = [tok.lower() for tok in tokenized_text if tok not in punctuation and tok not in stopwords]
bow.append(Counter(clean_text))
# Program freezes here
df_bows = pd.DataFrame.from_dict(bow)
My input would be a list of tokens of length num_samples where each text sample is a list of tokens. For my output I want a pandas DataFrame with shape (num_samples, 10000) where 10000 is the size of my vocabulary. Before, my df_bows vocabulary size (df_bows.shape[1]) would get very large (greater than 50,000.
How can I choose the 10,000 most frequently occurring words from my bow list of Counter objects and place then in a DataFrame while preserving number of text samples?