pandas–数据分析处理库
pandas是基于numpy构建的,为时间序列分析提供了很好的支持。pandas中有两个主要的数据结构,一个是Series,另一个是DataFrame。
-
导入pandas库,打开csv文件
import pandas
food_info = pandas.read_csv(“food_info.csv”)
print(type(food_info)) —<class ‘pandas.core.frame.DataFrame’> #查看文件的格式
#print(food_info.dtypes) #查看每一列数据的格式 -
使用函数head( m )来读取前m条数据,如果没有参数m,默认读取前五条数据;由于DataFrame包含了很多的行和列,Pandas使用省略号(…)来代替显示全部的行和列,可以使用colums属性来显示全部的列名;与Numpy一样,用shape属性来显示数据的格式。
tail(n)-----读取数据后n行
shape-----显示当前有多少样本,以及样本有多少个指标(列)
first_rows = food_info.head()
print(first_rows)
print(food_info.head(3))
print(food_info.columns)
print(food_info.shape) -
Pandas使用loc[]方法来选择行的数据(当超出索引值,将报错)
print(food_info.loc[0]) #取第一个数据
print(food_info.loc[6]) #取第七个数据
print(food_info.loc[8620]) #报错 -
#object - For string values object----在pandas中就是string类型
#int - For integer values
#float - For float values
#datetime - For time values
#bool - For Boolean values
print(food_info.dtypes) #输出所有列的字符类型 -
返回一个DataFrame,其中包含索引3、4、5和6处的行。
print(food_info.loc[3:6]) #取第3,4,5,6行数据返回一个DataFrame,其中包含索引2、5和10处的行(两个方法可以实现)
方法一:two_five_ten = [2,5,10]
print(food_info.loc[two_five_ten])
方法二:two_five_ten = [2,5,10]
print(food_info.loc[[2,5,10]]) -
表示“NDB_No”列的Series对象
ndb_col = food_info[“NDB_No”]
print(ndb_col)
或者,可以通过传入字符串变量来访问列。
col_name = “NDB_No”
ndb_col = food_info[col_name]
print(ndb_col) -
取指定两列的值
columns = [“Zinc_(mg)”, “Copper_(mg)”]
zinc_copper = food_info[columns]
print(zinc_copper)
或者这样也可以实现
zinc_copper = food_info[[“Zinc_(mg)”, “Copper_(mg)”]]
print(zinc_copper)
-
可以使用tolist()函数转化为list
print(food_info.columns) #输出所有列
print(food_info.head(2)) #输出前两行col_names = food_info.columns.tolist() #输出所有列
print(col_names) -
输出所有以g结尾的列的前三行
gram_columns = []
for c in col_names:
if c.endswith("(g)"):
gram_columns.append©
gram_df = food_info[gram_columns]
print(gram_df.head(3))