Python学习第二十一天,Pandas学习(三)

203 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第21天,点击查看活动详情

数据读取

数据读取是Pandas里一个十分常用的操作

Excel

函数格式:

pd.read_excel(io ,sheet_name ,header)
io:表示.xls.xlsx文件路径或类文件对象.  
sheet_name:表示工作表,取值如下表所示  
header:默认值为0,取第一行的值为列名,数据为除列名以外的数据
        如果数据不包含列名,则设置header=None
说明
sheet_name = 0读取当前表的第一个sheet页
sheet_name = 1读取当前表的第二个sheet页
sheet_name = "python"读取当前表中,sheet页名对应的
sheet_name = [0 ,"Python" ,"Java"]读取当前表中第一个sheet页以及页面对应的sheet页
sheet_name = None读取所有sheet页

举个例子:

df_1 = pd.read_excel(r"house.xlsx",header=0)
print(df_1.head())

结果:

image.png

解决一下过长Excel列显示的问题:

# 不换行显示
pd.set_option('display.width', 1000)

# 设置None则无列数的显示限制
pd.set_option('display.max_columns', None)

# 设置value的显示长度为100,默认为50
pd.set_option('max_colwidth', 80)

# 解决列名与名字不对齐
pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)

df_1 = pd.read_excel(r"house.xlsx",header=0)
print(df_1.head())

效果:

image.png

CSV

函数格式:

pd.read_csv(filepath_or_buffer,sep=,header,encoding=None)
filepath_or_buffer:字符串、文件路径,也可以是URL链接
sep:每行数据内容的分割符号字符串、分隔符,CSV常用’,’
header:指定作为列名的行,默认值为0,即取第一行的值为列名。
        数据为除列名以外的数据,若数据不包含列表,则设置header=None
names:用来指定列的名称,类似于列表的序列,不允许有重复值
usecols:用来获取指定列名的的数据
skip_blank_lines:跳过指定行数
nrows:用于指定需要读取的行数,常用于较大的数据
encoding:字符串,默认值为None,文件的编码格式

举个例子:

# 不换行显示
pd.set_option('display.width', 1000)

# 设置None则无列数的显示限制
pd.set_option('display.max_columns', None)

# 设置value的显示长度为100,默认为50
pd.set_option('max_colwidth', 80)

# 解决列名与名字不对齐
pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)


df_2 = pd.read_csv("双十一淘宝美妆数据.csv",encoding = "utf-8")
print(df_2.head())

结果:

image.png

小结

两种数据格式的读取方式很相像,为了方便显示以及编程,都可以加一连串的代码显示。不过需要注意的是csv格式文件本质上是文本文件与excel文件还是有区别的,需要注意。