1.2 Loading the data
Many applications can read files in Excel format, and pandas can too. Asking the computer to read the data looks like this:
In []:
data = read_excel('WHO POP TB some.xls')
data
Out[]:
Country | Population (1000s) | TB deaths | |
---|---|---|---|
0 | Angola | 21472 | 6900 |
1 | Brazil | 200362 | 4400 |
2 | China | 1393337 | 41000 |
3 | Equatorial Guinea | 757 | 67 |
4 | Guinea-Bissau | 1704 | 1200 |
5 | India | 1252140 | 240000 |
6 | Mozambique | 25834 | 18000 |
7 | Portugal | 10608 | 140 |
8 | Russian Federation | 142834 | 17000 |
9 | Sao Tome and Principe | 193 | 18 |
10 | South Africa | 52776 | 25000 |
11 | Timor-Leste | 1133 | 990 |
The variable name data is not descriptive, but as there is only one dataset in our analysis, there is no possible confusion with other data, and short names help to keep the lines of code short.
The function read_excel() takes a file name as an argument and returns the table contained in the file. In pandas, tables are called dataframes . To load the data , I simply call the function and store the returned dataframe in a variable.
A file name must be given as a string , a piece of text surrounded by quotes. The quote marks tell Python that this isn’t a variable, function or module name. Also, the quote marks state that this is a single name, even if it contains spaces, punctuation and other characters besides letters.
Misspelling the file name, or not having the file in the same folder as the notebook containing the code, results in a file not found error. In the example below there is an error in the file name.
In []:
data = read_excel('WHO POP TB same.xls')
data
---------------------------------------------
FileNotFoundError Traceback (most recent call last)
----> 1 data = read_excel(‘WHO POP TB same.xls’)
2 data
/Users/mw4687/anaconda/lib/python3.4/site-packages/pandas/io/excel.py in read_excel(io, sheetname, **kwds)
130 engine = kwds.pop(‘engine’, None)
131
--> 132 return ExcelFile(io, engine=engine).parse(sheetname=sheetname, **kwds)
133
134
/Users/mw4687/anaconda/lib/python3.4/site-packages/pandas/io/excel.py in __init__(self, io, **kwds)
167 self.book = xlrd.open_workbook(file_contents=data)
168 else:
--> 169 self.book = xlrd.open_workbook(io)
170 elif engine == ‘xlrd’ and isinstance(io, xlrd.Book):
171 self.book = io
/Users/mw4687/anaconda/lib/python3.4/site-packages/xlrd/__init__.py in open_workbook(filename, logfile,
verbosity, use_mmap, file_contents, encoding_override, formatting_info, on_demand, ragged_rows)
392 peek = file_contents[:peeksz]
393 else:
--> 394 f = open(filename, "rb")
395 peek = f.read(peeksz)
396 f.close()
FileNotFoundError: [Errno 2] No such file or directory: ‘WHO POP TB same.xls’
Jupyter notebooks show strings in red. If you see red characters until the end of the line, you have forgotten to type the second quote that marks the end of the string.
In the next section, find out how to select a column.