I am importing a .tsv file and creating a feature matrix using sklearn. This works perfectly. Code is below:
import nltk, string, csv, operator, re, collections, sys, struct, zlib, ast, io, math, time
from nltk.corpus import stopwords
import pandas as pd
# This function removes numbers from an array
def remove_nums(arr):
# Declare a regular expression
pattern = '[0-9]'
# Remove the pattern, which is a number
arr = [re.sub(pattern, '', i) for i in arr]
# Return the array with numbers removed
return arr
# This function cleans the passed in paragraph and parses it
def get_words(para):
# Create a set of stop words
stop_words = set(stopwords.words('english'))
# Split it into lower case
lower = para.lower().split()
# Remove punctuation
no_punctuation = (nopunc.translate(str.maketrans('', '', string.punctuation)) for nopunc in lower)
# Remove integers
no_integers = remove_nums(no_punctuation)
# Remove stop words
dirty_tokens = (data for data in no_integers if data not in stop_words)
# Ensure it is not empty
tokens = [data for data in dirty_tokens if data.strip()]
# Ensure there is more than 1 character to make up the word
tokens = [data for data in tokens if len(data) > 1]
# Return the tokens
return tokens
def main():
tsv_file = "C:\\Users\\Kelly\\Desktop\\Programming Assignment 4\\train.tsv"
print(tsv_file)
csv_table=pd.read_csv(tsv_file, sep='\t')
csv_table.columns = ['rating', 'ID', 'text']
s = pd.Series(csv_table['text'])
new = s.str.cat(sep=' ')
vocab = get_words(new)
from sklearn.feature_extraction.text import TfidfVectorizer
s = pd.Series(csv_table['text'])
corpus = s.apply(lambda s: ' '.join(get_words(s)))
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)
df = pd.DataFrame(data=X.todense(), columns=vectorizer.get_feature_names())
dfshape = df.shape
csvshape = csv_table.shape
print("SHAPE OF DF: {}".format(dfshape))
print("SHAPE OF CSV_TABLE: {}".format(csvshape))
print(df)
print(csv_table)
main()
That code creates the two dataframes, csv_table
and df
, which have the following shapes:
SHAPE OF DF: (1999, 12287)
SHAPE OF CSV_TABLE: (1999, 3)
An example of the .tsv
file looks like:
0 abch7619 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 42Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat…..........
1 uewl0928 Duis aute irure d21olor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excep3teur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
0 ahwb3612 Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur
1 llll2019 adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur???? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
0 jdne2319 At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.
1 asbq0918 Et harum quidem rerum facilis est et expedita distinctio................................ Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut
An example of csv_table
looks like:
rating ID text
0 2 BIeDBg4MrEd1NwWRlFHLQQ Decent but terribly inconsistent food. I've ha...
1 4 NJHPiW30SKhItD5E2jqpHw Looks aren't everything....... This little di...
2 2 nnS89FMpIHz7NPjkvYHmug Being a creature of habit anytime I want good ...
An example of df
looks like:
aaargh aah aaron aback abacus abandon abandoned abc ability ablaze able aboard abode ... zippys ziti zitti zoes zombified zomg zoo zoom zsa zsu ztejas zucchini zuppa
0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
1 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
4 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
5 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ...
However, what I now need to accomplish is to merge df
and csv_table
to create a true dataset of the proper classification, the ID, and the feature matrix for each class/ID combo that was just created.
I tried looking at this SO Post but that did not yield me anything worthwhile.
I also look into Pandas JOIN but I don't have an index
or a key
column (at least I don't think)
So how is it achievable to merge the two without JOIN
since I don't have a key or index?