Pandas Cheat Sheet Rev2

A Programming › Python cheat sheet in English by dstark0011

Pandas Cheat Sheet Extra text to meet the character requirements

6,287 views 2,026 downloads 27 Nov 2020 History

Import Data

df = pd.rea­d_c­sv­­('f­­ile­­na­m­e.cs­v')
Read CSV into a Pandas DataFrame
df = pd.to_­csv­('f­­ile­­na­m­e.cs­v')
Export Pandas DataFrame to CSV
Import Options:

header­=False, Index=­False, usecol­s=(5,6)

Can also read CSV / HTML / Excel / JSON

Combine multiple files into one (1) DataFrame

all_files = glob.glob(*/.txt')
Finds all txt files in the
df_raw = [pd.re­ad_­csv(f) for f in all_files]
Makes multiple DataFrames
df_all = pd.con­cat­(df­_raw, ignore­_in­dex­=True
Concat­enates all the DataFrames into one (1) large DataFrame

Select Data

df.head(5)
Reads the first 5 rows
df.tail(5)
Reads the last 5 rows
df.shape()
Gives the number of columns and rows in the DataFrame

Select Row

data.i­loc[0]
First row of DataFrame
data.i­loc[1]
Second row of DataFrame

Select Column

data.i­loc[:0]
First column of DataFrame
data.i­loc[:1]
Second column of DataFrame

Select Column and Row Combined

df.ilo­c[:3, :2]
Selecting first 3 rows and first 2 columns
df.ilo­c[:3, ['Co­lum­n1', '­Col­umn­2']]
Selecting first 3 rows and first 2 columns

Re-Order Colums

df = df[['Co­lum­n3', '­Col­umn­2', '­Col­umn­1']]
Re-orders the columns to the order specified in this list

Drop Columns

df= df.dro­p(c­olu­mns­=['C­olu­mn1­'], axis=1)
Drops '­Col­umn­1_N­ame­' from DataFrame

Sort Columns

df = df.sor­t_v­alu­es(­by=­['Co­lum­n1'], ascend­ing­=False)
Sort values by Column1

Filter Column

df= df[(df­­['C­­ol­u­m­n1'] >= some_n­­umber]
Filter DataFrame by certain value

Rename Columns

df.columns = ['A', '­B']
Renamed Columns to '­A' and '­B'

Merge DataFrames

df1.a­­ppe­­nd­(­df2)
Joins df1 and df2

Filter on Condition

df = df[(df> 2).all­(ax­is=1)]
Removes any values less than 2

Select Row Based on Condition

row = df[df.A > 3].iloc[0]
Select first row where A > 0

Dealing with NAN values

df= df.fil­lna­(me­tho­d='f­fil­l')
Fills blank values using forward fill method
df= df.fil­lna­(me­tho­d='b­fil­l')
Fills blank values using backwards fill method
df.dro­pna­(in­pla­ce=­True)
Removes rows with no values

Padding Values With Zero's

df['­Col­umn­1'] = df['­Col­umn­1'].a­st­ype­(st­r).s­tr.zf­ill(6)
Sets the numbe to six (6) long, which adds zeros

Change Column Data Type

df['­Col­umn­1']= df['­Col­umn­1'].a­st­ype­(float)
Change '­Col­umn­1' to float

Convert Column to Date / Time

df['­Tim­e'] = df['­Tim­e'].a­pp­ly(­pd.t­o_­dat­etime)
Converts the time column to a Datetime Series

Comments

No comments yet.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.