code
import pandas
table_info = pandas.read_csv("./Desktop/table.csv")
print(type(table_info))
注释
import pansas : 导入pandas库,类似于c语言的#include
pandas.read_csv():读取csv文件,参数可谓绝对路径,也可为相对路径。
这里使用的是Anaconda的 Jupyter Notebook,当前.py路径为本机的home路径,待导入的文件相对于home的路径为./Desktop/table.csv。
初次接触竟然没找到文件的相对路径。复制了windows的绝对路径(C:\Users\ddx\Desktop\table.csv),但是一直提示"SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated \UXXXXXXXX escape"
后来发现复制的路径是windows模式的路径采用的分隔符是’’,而pandas路径采用的分隔符是’/’.
pandas 数据读取函数
以上述导入的数据table_info为例, pandas导入的数据类似于二维数组。而这个数组读取函数的调用方式比较像成员函数,如取前两行和后两行的方式如下
table_info.head(2)
table_info.tail(2)
与二维数组不同的是,pandas会将导入数据的第一行默认为标题行,每一列的数据类型一致,而不同列的数据类型不一致。可以调用columns获取数据的标题行:
table_info.columns
table_info.loc[0:2]
table_info.loc[0]
table_info[“a”]
col_name = table_info.columns.tolist()
print(col_name)
gram_colums = []
for c in col_name:
if c.endswith("(g)"):
gram_colums.append©
print(gram_colums)
gram_df = table_info[gram_colums]
gram_df.head()