f0rd42 f0rd42 - 2 months ago 13
Python Question

Python Pandas: Read specific columns from cdv, then reorder

I have a csv which I need to manipulated and write back.
I only want specific columns (with header) and re-order them.

I use:

fields = ['Ticket Number', 'Created', 'Closed', 'CustomerID', 'Customer Realname']
df = pd.read_csv('args.inname', sep=',', skipinitialspace=True, usecols=fields, columns='Created', 'Ticket Number', 'Customer Realname', 'CustomerID', 'Closed')
df = df.rename(columns={'Ticket Number': 'CaseNumber', 'Created': 'CreationDate', 'Closed': 'ClosedDate', 'CustomerID': 'EndCustomerEmail', 'Customer Realname': 'EndCustomerName'})


but it throws a


SyntaxError: positional argument follows keyword argument


right after the second line after I expanded it with "column=" to re-order immediately after reading

I'm sure I'm missing something obvious here but can't find it.

Answer

Try this:

# specify your columns in the order you want to have it in the ouptut file
fields = ['Ticket Number', 'Created', 'Closed', 'CustomerID', 'Customer Realname']

df = pd.read_csv('args.inname', sep=',', skipinitialspace=True, usecols=fields)[fields]

df = df.rename(columns={'Ticket Number': 'CaseNumber', 'Created': 'CreationDate', 'Closed': 'ClosedDate', 'CustomerID': 'EndCustomerEmail', 'Customer Realname': 'EndCustomerName'})
Comments