|
| 1 | +""" BASICS OF DATA ANALYSIS """ |
| 2 | + |
| 3 | + |
| 4 | +# with open('./weather_data.csv', 'r') as file: |
| 5 | +# data = file.readlines() |
| 6 | +# print(data) |
| 7 | +"""There is a lot of headache in cleaning the above data, so try other way (see below)""" |
| 8 | + |
| 9 | + |
| 10 | +# import csv |
| 11 | +# with open('./weather_data.csv') as data_file: |
| 12 | +# data = csv.reader(data_file) |
| 13 | +# temperatures = [] |
| 14 | +# for row in data: |
| 15 | +# if row[1] != 'temp': |
| 16 | +# temperatures.append(int(row[1])) |
| 17 | +# |
| 18 | +# print(temperatures) |
| 19 | +""" |
| 20 | +A lot of lines of code is written just to get one column, what if there are 100s of columns and complex data, |
| 21 | +so it is not a convenient way. Now let's use PANDAS library and see the magic. |
| 22 | +""" |
| 23 | + |
| 24 | + |
| 25 | +import pandas as pd |
| 26 | +data = pd.read_csv('./weather_data.csv') |
| 27 | +print(data['temp']) |
| 28 | + |
| 29 | +# DataFrame: whole table of Excel sheet or google sheet (2D) |
| 30 | + # eg: data |
| 31 | +# Series: a column of Excel sheet or google sheet (1D) |
| 32 | + # eg: data['temp'] |
| 33 | + |
| 34 | +data_as_dict = data.to_dict() |
| 35 | +temp_list = data['temp'].to_list() |
| 36 | +print(data_as_dict) |
| 37 | +print(temp_list) |
| 38 | + |
| 39 | + |
| 40 | +print('Average Temperature: ', sum(temp_list)/len(temp_list)) |
| 41 | +print('Average temp using series: ', data['temp'].mean()) |
| 42 | +print('Max temp using series: ', data['temp'].max()) # data['temp'] == data.temp |
| 43 | +print('Max temp using series: ', data.temp.max()) |
| 44 | +print(data.condition) |
| 45 | + |
| 46 | + |
| 47 | +# Get data in row |
| 48 | +print(data[data.day == 'Monday']) # its dataframe |
| 49 | + |
| 50 | +# Get the row which has maximum temperature |
| 51 | +print(data[data.temp == data.temp.max()]) # its dataframe |
| 52 | + |
| 53 | +# Get Monday's condition |
| 54 | +print(data[data.day == "Monday"].condition) |
| 55 | + |
| 56 | +# challenge: show Monday's temperature in Fahrenheit ((0°C × 9/5) + 32 = 32°F) |
| 57 | +monday_temp = data.temp[0] |
| 58 | +print(monday_temp) |
| 59 | +print("Monday's temp in Fahrenheit: ", monday_temp * 9/5 + 32, "°F") |
| 60 | + |
| 61 | + |
| 62 | +# create a DataFrame from scratch |
| 63 | +data_dict = { |
| 64 | + "names": ['Amit', 'Rohit', 'Sumit'], |
| 65 | + "score": [45, 73, 66] |
| 66 | +} |
| 67 | +df_from_scratch = pd.DataFrame(data_dict) |
| 68 | +print(df_from_scratch) |
| 69 | + |
| 70 | + |
| 71 | +# save the DataFrame in csv format |
| 72 | +df_from_scratch.to_csv('./students_data.csv') # path where you want to save |
0 commit comments