Professional Documents
Culture Documents
What is Pandas?
Pandas is an opensource library that allows to you perform data manipulation in Python. Pandas
library is built on top of Numpy, meaning Pandas needs Numpy to operate. Pandas provide an
easy way to create, manipulate and wrangle the data. Pandas is also an elegant solution for time
series data.
Why use Pandas?
Data scientists use Pandas for its following advantages:
Easily handles missing data
It uses Series for one-dimensional data structure and DataFrame for multi-dimensional
data structure
It provides an efficient way to slice the data
It provides a flexible way to merge, concatenate or reshape the data
It includes a powerful time series tool to work with
In a nutshell, Pandas is a useful library in data analysis. It can be used to perform data
manipulation and analysis. Pandas provide powerful and easy-to-use data structures, as well as the
means to quickly perform operations on these structures.
What is a data frame?
A data frame is a two-dimensional array, with labeled axes (rows and columns). A data frame is a
standard way to store data.
Data frame is well-known by statistician and other data practitioners. A data frame is a tabular data,
with rows to store the information and columns to name the information. For instance, the price can
be the name of a column and 2,3,4 the price values.
Below a picture of a Pandas data frame:
What is a Series?
A series is a one-dimensional data structure. It can have any data structure like integer, float, and
string. It is useful when you want to perform computation or return a one-dimensional array. A
series, by definition, cannot have multiple columns. For the latter case, please use the data frame
structure.
Series has one parameters:
Data: can be a list, dictionary or scalar value
pd.Series([1., 2., 3.])
0 1.0
1 2.0
2 3.0
dtype: float64
You can add the index with index. It helps to name the rows. The length should be equal to the size
of the column
pd.Series([1., 2., 3.], index=['a', 'b', 'c'])
Below, you create a Pandas series with a missing value for the third rows. Note, missing values in
Python are noted "NaN." You can use numpy to create missing value: np.nan artificially
pd.Series([1,2,np.nan])
Output
0 1.0
1 2.0
2 NaN
dtype: float64
## Numpy to pandas
import numpy as np
h = [[1,2],[3,4]]
df_h = pd.DataFrame(h)
print('Data Frame:', df_h)
## Pandas to numpy
df_h_n = np.array(df_h)
print('Numpy array:', df_h_n)
Data Frame: 0 1
0 1 2
1 3 4
Numpy array: [[1 2]
[3 4]]
0 30 John
1 40 Smith
Range Data
Pandas have a convenient API to create a range of date
pd.data_range(date,period,frequency):
The first parameter is the starting date
The second parameter is the number of periods (optional if the end date is specified)
The last parameter is the frequency: day: 'D,' month: 'M' and year: 'Y.'
## Create date
# Days
dates_d = pd.date_range('20300101', periods=6, freq='D')
print('Day:', dates_d)
Output
Day: DatetimeIndex(['2030-01-01', '2030-01-02', '2030-01-03', '2030-01-04', '2030-01-05', '2030-01
-06'], dtype='datetime64[ns]', freq='D')
# Months
dates_m = pd.date_range('20300101', periods=6, freq='M')
print('Month:', dates_m)
Output
Month: DatetimeIndex(['2030-01-31', '2030-02-28', '2030-03-31', '2030-04-30','2030-05-31', '2030-
06-30'], dtype='datetime64[ns]', freq='M')
Inspecting data
You can check the head or tail of the dataset with head(), or tail() preceded by the name of the
panda's data frame
Step 1) Create a random sequence with numpy. The sequence has 4 columns and 6 rows
random = np.random.randn(6,4)
Step 2) Then you create a data frame using pandas.
Use dates_m as an index for the data frame. It means each row will be given a "name" or an index,
corresponding to a date.
Finally, you give a name to the 4 columns with the argument columns
# Create data with date
df = pd.DataFrame(random,
index=dates_m,
columns=list('ABCD'))
Step 3) Using head function
df.head(3)
A B C D
2030-01-31 -0.168655
2030-02-28 0.689585
2030-03-31 0.767534
2030-04-30 0.557299
2030-05-31 -1.547836
2030-06-30 0.511551
Freq: M, Name: A, dtype: float64
To select multiple columns, you need to use two times the bracket, [[..,..]]
The first pair of bracket means you want to select columns, the second pairs of bracket tells what
columns you want to return.
df[['A', 'B']].
A B
Drop a column
You can drop columns using pd.drop()
df.drop(columns=['A', 'C'])
B D
Concatenation
You can concatenate two DataFrame in Pandas. You can use pd.concat()
First of all, you need to create two DataFrames. So far so good, you are already familiar with
dataframe creation
import numpy as np
df1 = pd.DataFrame({'name': ['John', 'Smith','Paul'],
'Age': ['25', '30', '50']},
index=[0, 1, 2])
df2 = pd.DataFrame({'name': ['Adam', 'Smith' ],
'Age': ['26', '11']},
index=[3, 4])
Finally, you concatenate the two DataFrame
df_concat = pd.concat([df1,df2])
df_concat
Age name
0 25 John
1 30 Smith
2 50 Paul
3 26 Adam
4 11 Smith
Drop_duplicates
If a dataset can contain duplicates information use, `drop_duplicates` is an easy to exclude
duplicate rows. You can see that `df_concat` has a duplicate observation, `Smith` appears twice in
the column `name.`
df_concat.drop_duplicates('name')
Age name
0 25 John
1 30 Smith
2 50 Paul
3 26 Adam
Sort values
You can sort value with sort_values
df_concat.sort_values('Age')
Age name
4 11 Smith
0 25 John
3 26 Adam
1 30 Smith
2 50 Paul
0 25 John
1 30 Smith
2 50 Paul
3 26 Adam
4 11 Smith