Use of pandas for dataframe
-
first : import the package to be used:
import pandas as pd
import numpy as np -
read csv file into python environment
data1 = pd.read_csv("data1.csv")
- overview the structure and characters of the dataframe.
data1.head() #default 5 rows, another wanted number is avaiable.
data1.tail(4) #display the last 4 rows in the dataframe.
data1.columns() #list the names of columns in the dataframe.
data1.shape() #similar with numpy, get the amount of columns and rows in a form of (rows, columns)
- index in a pandas dataframe.
data1.loc[0] # specify the first observation, the number must be less than the max row number.
data1.loc["var1"] #index a column in pandas dataframe.
# -------select specific columns---------
col_names = data1.columns.tolist()
wanted_columns = []
for c in col_names:
if c.endswith("(g)"):
wanted_columns.append(c)
wanted_df = data1[wanted_columns]
print(wanted_df.head(3))
#-----------------------------------------------
- insert a variable into a pandas dataframe(the number of rows must be consistent)
data1["var_name"] = var
- index the max or min value in a column
data1["column_name"].max()