3

I had a question about reading in a column name from a CSV file into my python program starting with a number? So my CSV datafile called Teams.csv has columns with names or headers such as R, AB, H, 2B, 3B, etc. Specifically, the CSV file is the Lahman's Baseball Database's Teams.csv file.

Now when I read this file in Python, I use this:

#imported pandas as pd
df = pd.read_csv("Teams.csv")

#Get stats for offense
R = df.R
AB = df.AB
H = df.H

and these work fine, but when I try to import 2B and 3B though

doubles = df.2B
triples = df.3B

these give a syntax error because of Python not having variables start with digits.

Is there a way around this that I can do within Python itself? Or do I have to go into the CSV and rename the headers to lets say X2B and X3B?

I rather not do the latter, because Lahman's Baseball Database has A LOT of CSV files.

5
  • would it be possible, to change map them into strings and save to variables, like variable = str(2B)? Commented May 24, 2016 at 9:51
  • 1
    I don't know Panda DataFrame. But maybe you can do df["2B"]. Commented May 24, 2016 at 9:53
  • unfortunately not -- if I end up doing df.variable, it'll look for variable as the column header Commented May 24, 2016 at 9:55
  • Isn't that what you want? Aren't 2B etc. column headers? Don't you want to get columns? Commented May 24, 2016 at 9:57
  • I strongly suggest you don't use dot notation to access columns as it becomes ambiguous if you're trying to access a column, an attribute or a method on the df Commented May 24, 2016 at 9:57

2 Answers 2

3

You can use bracket notation:

doubles = df['2B']
triples = df['3B']
Sign up to request clarification or add additional context in comments.

Comments

1

IIUC and if you would prefer to access the columns by dot notation, to rename the column names conditionally:

#Check if a column name is starting with digit and 
#if it is starting rearrange column name to start with a character
df.columns = [ ''.join([x[1],x[0]]) if re.match('^\d',x) else x for x in df.columns]

Will produce this result:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.