Reading in Different File Types

Reading in Different File Types

pandas facilitates the loading of data from many different file types including:

  • A URL
  • A txt file
  • An xlsx file

Reading from a URL

https://raw.githubusercontent.com/UBC-MDS/MCL-DSCI-011-programming-in-python/master/data/candybars.csv.

404 image


candybars = pd.read_csv('https://raw.githubusercontent.com/UBC-MDS/MCL-DSCI-511-programming-in-python/master/data/candybars.csv')
candybars.head()
name weight chocolate peanuts ... coconut white_chocolate multi available_canada_america
0 Coffee Crisp 50 1 0 ... 0 0 0 Canada
1 Butterfinger 184 1 1 ... 0 0 0 America
2 Skor 39 1 0 ... 0 0 0 Both
3 Smarties 45 1 0 ... 0 0 1 Canada
4 Twix 58 1 0 ... 0 0 1 Both

5 rows × 11 columns

Reading in a Text File

candybars = pd.read_csv('data/candybars-text.txt')
candybars.head()
name\tweight\tchocolate\tpeanuts\tcaramel\tnougat\tcookie_wafer_rice\tcoconut\twhite_chocolate\tmulti\tavailable_canada_america
0 Coffee Crisp\t50\t1\t0\t0\t0\t1\t0\t0\t0\tCanada
1 Butterfinger\t184\t1\t1\t1\t0\t0\t0\t0\t0\tAme...
2 Skor\t39\t1\t0\t1\t0\t0\t0\t0\t0\tBoth
3 Smarties\t45\t1\t0\t0\t0\t0\t0\t0\t1\tCanada
4 Twix\t58\t1\t0\t1\t0\t1\t0\t0\t1\tBoth


candybars = pd.read_csv('data/candybars-text.txt', delimiter='\t')
candybars.head()
name weight chocolate peanuts ... coconut white_chocolate multi available_canada_america
0 Coffee Crisp 50 1 0 ... 0 0 0 Canada
1 Butterfinger 184 1 1 ... 0 0 0 America
2 Skor 39 1 0 ... 0 0 0 Both
3 Smarties 45 1 0 ... 0 0 1 Canada
4 Twix 58 1 0 ... 0 0 1 Both

5 rows × 11 columns

Reading in an Excel File (xlsx)

candybars = pd.read_excel('data/foods.xlsx', sheet_name='chocolate')
candybars
name weight chocolate peanuts ... coconut white_chocolate multi available_canada_america
0 Coffee Crisp 50 1 0 ... 0 0 0 Canada
1 Butterfinger 184 1 1 ... 0 0 0 America
2 Skor 39 1 0 ... 0 0 0 Both
... ... ... ... ... ... ... ... ... ...
22 Almond Joy 46 1 0 ... 1 0 0 America
23 Oh Henry 51 1 1 ... 0 0 0 Both
24 Cookies and Cream 43 0 0 ... 0 1 0 Both

25 rows × 11 columns

Reading in Data from a Different File

404 image

This translates to the syntax data/canucks.csv.

Example:

data/module3/question2/candybars.csv



404 image
404 image

Let’s apply what we learned!