我正在尝试创建一个文件,该文件仅包含文件 1 中的名称而不包含文件 1 中的名称。运行以下代码时出现错误:
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])
错误:
---------------------------------------------------------------------------
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__'
当我在 range(1) 中设置 i 并且只运行 1 次迭代时,该代码有效,但不适用于多行。
最佳答案
您已将 f
绑定(bind)到循环中的文件对象,因此在一次迭代后它不再指向您的 df
所以 f['First Name'] [i]
是 file_object['First Name'][i]
而不是 your_dataframe['First Name'][i]
所以它显然失败了:
with open('noshab.csv', 'a') as f: # <- f is now a file object
将名称从 f = pandas.read_csv('hillelclass2019.csv')
更改为 df = pandas.read_csv('hillelclass2019.csv')
并使用 df
引用代码中的数据框:
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
关于 if g['Name'][j] == x:
中的另一个注释 a == 1
什么都不做,我想你的意思是 a = 1
。
关于python - 解决类型错误 : 'file' object has no attribute '__getitem__' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32054809/