0

the following code reads the CSV file, pick the column GLTGV and converts the date from the US to UK. However it gives me an error AttributeError: 'Series' object has no attribute 'iterrows' . I tried to replace it by iteritems, but unsuccessfully. Can anyone help me with iteritems or propose alternate solution?

import pyodbc
import pandas
import os
import sys
import struct

try:
    currdir = os.path.abspath(__file__)
except NameError:  
    import sys
currdir = os.path.abspath(os.path.dirname(sys.argv[0]))
serverpath = os.path.join(currdir, 'serverlink.txt')

f=open(serverpath,"r")
lines=f.readlines()
servername=lines[0]
f.close()

print(servername)

serv = servername 
datab = 'BACKEND' 

cnxn = pyodbc.connect('Trusted_Connection=yes', driver = '{ODBC Driver 13 for SQL Server}',server = serv, database = datab)

import fileinput
import os
import csv
import pandas as pd

cwd = os.getcwd()

directory = (cwd + '\\')

for file in os.listdir(directory):
    if file.endswith( "USR02_FINAL.csv"):
        data = pd.read_csv(directory + "USR02_FINAL.csv", sep=",", usecols=['GLTGV'],  low_memory=False, encoding='latin-1')
        data = pd.to_datetime(data['GLTGV'], dayfirst=True, errors='coerce').dt.strftime("%d/%m/%Y").fillna("")    
print(data)
cursor = cnxn.cursor()
for index,row in data.iterrows():
    cursor.execute("INSERT INTO dbo.USR_02_ALL([GLTGV]) values(?)", row(['GLTGV']))
    cnxn.commit()
cursor.close()
cnxn.close()
user9799161
  • 123
  • 2
  • 14
  • Check [this answer](https://stackoverflow.com/questions/50267185/iterate-over-pandas-series/50267205#50267205). If you can't avoid using `iter` functions, then use `Series.iteritems`. – cs95 Jun 18 '19 at 17:16
  • When you pass a single column to the `to_csv` method, the result is a series, not a dataframe, which is why `iterrows` doesn't work. You state that you "tried to replace it by iteritems, but unsuccessfully". What does that mean? What did you try, and why didn't it work for you? – G. Anderson Jun 18 '19 at 17:30
  • i changed the `row` with `val` and `iterrows` with iteritems, but got errors `TypeError: 'str' object is not callable` or `pyodbc.DataError: ('22007', '[22007] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Conversion failed when converting date and/or time from character string. (241) (SQLExecDirectW)')`. – user9799161 Jun 18 '19 at 17:31

0 Answers0