Python_pandas读取数据

2022-09-30 10:39:25

pandas读取数据

三种数据文件的读取:
在这里插入图片描述

一、csv、tsv、txt 文件读取:
1)CSV文件读取: 语法格式:pandas.read_csv(文件路径)
CSV文件内容如下:
在这里插入图片描述

import pandas as pd
file_path = "e:\\pandas_study\\test.csv"
content = pd.read_csv(file_path)

content.head()  # 默认返回前5行数据
content.head(3)  # 返回前3行数据
content.shape  # 返回一个元组(总行数,总列数),总行数不包括标题行

content.index    #    返回索引,是一个可迭代的对象<class 'pandas.core.indexes.range.RangeIndex'>

content.column    #  返回所有的列名 Index(['姓名', '年龄', '籍贯'], dtype='object')

content.dtypes  #  返回的是每列的数据类型
姓名    object
年龄     int64
籍贯    object
dtype: object

2)CSV文件读取: 语法格式:pandas.read_csv(文件路径)
CSV文件内容如下:
在这里插入图片描述

import pandas as pd
file_path = "e:\\pandas_study\\test2.txt"

content = pd.read_csv(file_path,sep='\t',header = None ,names= ['name','age','adress'])
#参数说明:
# header = None 表示没有标题行
# sep='\t'  表示去除分割符中的空格
# names= ['name','age','adress'] ,列名依次自定义为'name','age','adress'

content.head()  # 默认返回前5行数据
content.head(3)  # 返回前3行数据
content.shape  # 返回一个元组(总行数,总列数),总行数不包括标题行

content.index    #    返回索引,是一个可迭代的对象<class 'pandas.core.indexes.range.RangeIndex'>

content.column    #  返回所有的列名 Index(['姓名', '年龄', '籍贯'], dtype='object')

content.dtypes  #  返回的是每列的数据类型

二、excel文件读取:
在这里插入图片描述

import pandas as pd
file_path = "e:\\pandas_study\\test3.xlsx"
content = pd.read_excel(file_path)

content.head()  # 默认返回前5行数据
content.head(3)  # 返回前3行数据
content.shape  # 返回一个元组(总行数,总列数),总行数不包括标题行

content.index    #    返回索引,是一个可迭代的对象<class 'pandas.core.indexes.range.RangeIndex'>

content.column    #  返回所有的列名 Index(['姓名', '年龄', '籍贯'], dtype='object')

content.dtypes  #  返回的是每列的数据类型
姓名    object
年龄     int64
籍贯    object
dtype: object

三、数据库表格读取:

语法: pandas.read_sql(sql语句,数据库连接对象)
数据对象的创建,可以根据pymysql,cx_oracle等模块连接mysql或者oracle。
代码省略。

  • 作者:小菜鸡也会有春天
  • 原文链接:https://blog.csdn.net/weixin_50640351/article/details/117336508
    更新时间:2022-09-30 10:39:25