Reputation: 237
I'm trying to create a file that includes the names only on file 1 and that are not on file 1. I get an error running the following code:
import pandas
import csv
f = pandas.read_csv('hillelclass2019.csv')
g = pandas.read_csv('shabsignup.csv')
for i in range(193): #length of data1
x = str(f['First Name'][i]) + " " + str(f['Last Name'][i]) #first name + last name
a = 0 #initial
for j in range(25): #length of data2
if g['Name'][j] == x: #if name == name on other sheet, then a == 1
a == 1
if a == 0: #if names are not equal
with open('noshab.csv', 'a') as f: #write name to file
wtr = csv.writer(f, delimiter= ',')
wtr.writerow( [x,i])
the error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/var/folders/kz/351q8p011qjc2x4k9srypcqc0000gn/T/tmpf4VgQX.py in <module>()
5 g = pandas.read_csv('shabsignup.csv')
6 for i in range(193): #length of data1
----> 7 x = str(f['First Name'][i]) + " " + str(f['Last Name'][i]) #first name + last name
8 a = 0 #initial
9 for j in range(25): #length of data2
TypeError: 'file' object has no attribute '__getitem__'
The code works when I set i in range(1) and only run 1 iteration, but does not work for multiple lines.
Upvotes: 2
Views: 1860
Reputation: 180411
You have bound f
to a file object in your loop so after one iteration it no longer points to your df
so f['First Name'][i]
is file_object['First Name'][i]
not your_dataframe['First Name'][i]
so it obviously fails:
with open('noshab.csv', 'a') as f: # <- f is now a file object
Change the name from f = pandas.read_csv('hillelclass2019.csv')
to df = pandas.read_csv('hillelclass2019.csv')
and use df
to refer to the dataframe in your code:
df = pandas.read_csv('hillelclass2019.csv')
g = pandas.read_csv('shabsignup.csv')
for i in range(193): #length of data1
x = str(df['First Name'][i]) + " " + str(df['Last Name'][i]) #first name + last name
On another note a == 1
inside the if g['Name'][j] == x:
is doing nothing, I presume you mean a = 1
.
Upvotes: 1
Reputation: 45243
The error is occurring because you are trying to access the file instance like a dict.
f['First Name']
or any other key access won't work on a file instance.
The error is referring to a __getitem__
function, which is called under the hood anytime to try to use []
to index into an object, usually a dict or similarly keyed structure.
Upvotes: 0