Friday, 12 April 2019

Creating Pandas DataFrame using CSV, Excel, Dictionary, List and Tuple

We can create pandas data frame in different ways. We can load data from CSV and Excel files. We can also create data frame using dictionary, lists and tuples. Following are some of the examples of loading data into pandas data frame:

Creating Pandas DataFrame using CSV

data_frame_csv = pd.read_csv("dataset.csv")
data_frame_csv 

Creating Pandas DataFrame using Excel Sheet

data_frame_xlsx = pd.read_excel("dataset.xlsx", "Sheet1")
data_frame_xlsx 

Note: You also have to specify sheet name of the Excel.

Creating Pandas DataFrame using Python Dictionary

dataset={
'day' : ['Sunday', 'Monday', 'Tuesday'],
'temperature' : [31, 25, 32],
'windspeed' : [6, 7, 5],
'event' : ['Rain', 'Sunny', 'Humid']
}

data_frame_dictionary = pd.DataFrame(dataset)
data_frame_dictionary

Creating Pandas DataFrame using Python List of Dictionary

dataset=[
{'day' : 'Sunday',  'temperature' : 31, 'windspeed' : 6, 'event' : 'Rain'},
{'day' : 'Monday', 'temperature' : 25, 'windspeed' : 7, 'event' : 'Sunny'},
{'day' : 'Tuesday', 'temperature' : 32, 'windspeed' : 5, 'event' : 'Humid'}
]

data_frame_dictionary_list = pd.DataFrame(dataset)
data_frame_dictionary_list

Creating Pandas DataFrame using Python List of Tuples

dataset=[
('Sunday',  31, 6, 'Rain'),
('Monday',  25, 7, 'Sunny'),
('Tuesday', 32, 5, 'Humid')
]

data_frame_tuple_list = pd.DataFrame(dataset, columns=['day', 'temperature', 'windspeed', 'event'])
data_frame_tuple_list

Note: You need to specify column names explicitly.

Documentation: Pandas IO Tools

No comments:

Post a Comment