pandas从文件读取数据

读取文件

读取csv,txt文件read_csv()

csv文件介绍:

  • CSV 又称逗号分隔值文件,是一种简单的文件格式,以特定的结构来排列表格数据。
  • CSV 文件能够以纯文本形式存储表格数据,比如电子表格、数据库文件,并具有数据交换的通用格式。
  • CSV 文件会在 Excel 文件中被打开,其行和列都定义了标准的数据格式。

读取方法:

  • pandas.read_csv(filepath_or_buffer, sep =‘,’, header=0, names=[“第一列”,“第二列”,“第三列”],encoding=‘utf-8’,usecols=[1,2,3])
  • filepath_or_buffer: 文件路径
  • sep:原文件的分隔符
  • header: 用作列名的行号,默认为header=0,即使用首行作为列名;若header=None,则表明数据中没有列名行
  • names:列名命名或重命名,当指定了列名以后,还是可以用0,1,2等index进行列的访问
  • usecols:要读取的列号或列名,不能用切片的方式
    其它参数参照read_excel
import pandas as pd
df = pd.read_csv(".\study\weather.txt", sep=",")
print("df------\n", df.head())
df1 = pd.read_csv(".\study\weather.txt", sep=",", names=["a", "b", "c", "d", "e","f", "g", "h", "i"], usecols=[1, 2, 3, 4, 5]) #指定列号
print("df1------\n",df1.head())
df2 = pd.read_csv(".\study\weather.txt", sep=",", names=["a", "b", "c", "d", "e","f", "g", "h", "i"], usecols=["b", "d", "e"]) #指定列名
print("df2------\n",df2.head())
df------
           ymd bWendu yWendu tianqi fengxiang fengli  aqi aqiInfo  aqiLevel
0  2018-01-01     3℃    -6℃   晴~多云       东北风   1-2级   59       良         2
1  2018-01-02     2℃    -5℃   阴~多云       东北风   1-2级   49       优         1
2  2018-01-03     2℃    -5℃     多云        北风   1-2级   28       优         1
3  2018-01-04     0℃    -8℃      阴       东北风   1-2级   28       优         1
4  2018-01-05     3℃    -6℃   多云~晴       西北风   1-2级   50       优         1
df1------
         b       c       d          e       f
0  bWendu  yWendu  tianqi  fengxiang  fengli
1      3℃     -6℃    晴~多云        东北风    1-2级
2      2℃     -5℃    阴~多云        东北风    1-2级
3      2℃     -5℃      多云         北风    1-2级
4      0℃     -8℃       阴        东北风    1-2级
df2------
         b       d          e
0  bWendu  tianqi  fengxiang
1      3℃    晴~多云        东北风
2      2℃    阴~多云        东北风
3      2℃      多云         北风
4      0℃       阴        东北风

读取excel文件read_excel ()

使用库介绍:

  • pandas.read_excel () 在内部使用名为 openpyxl 和 xlrd 的库。

读取方法:

  • pandas.read_excel(
    io,
    sheet_name=0,
    header=0,
    names=None,
    index_col=None,
    usecols=None,
    skiprows=None,
    nrows=None
    )

参数介绍:

  • io: 文件路径
  • sheet_name: 文件路径
    • 默认是0,索引号从0开始,表示第一个sheet。返回DataFrame。
    • sheet_name=1, 2nd sheet as a DataFrame。
    • sheet_name=“sheet1”,Load sheet with name “Sheet1”。
    • sheet_name=[1,2,“sheet3”],Load first, second and sheet named “Sheet3”,返回dict类型,key名为1,2,“sheet3”。
    • None 表示引用所有sheet,返回dict类型,key为sheet名。

  • header:表示用第几行作为表头,支持 int, list of int;
    默认是0,第一行的数据当做表头。header=None表示不使用数据源中的表头,Pandas自动使用0,1,2,3…的自然数作为索引。
  • names:表示自定义表头的名称,此时需要传递数组参数。
  • index_col:指定列属性为行索引列,支持 int, list of int, 默认是None,也就是索引为0,1,2,3等自然数的列用作DataFrame的行标签。
    如果传入的是列表形式,则行索引会是多层索引。

  • usecols:待解析的列,支持 int, str, list-like, or callable ,默认是 None,头尾皆包含。
    • If None, 表示解析全部的列。
    • If str, then indicates comma separated list of Excel column letters
      and column ranges (e.g. “A:E” or “A,C,E:F”). Ranges are inclusive of
      both sides.
    • If list of int, then indicates list of column numbers to be parsed.
    • If list of string, then indicates list of column names to be parsed.

  • dtype:指定列属性的字段类型。案例:{“a”: “float64”};默认为None,也就是不改变数据类型。
  • skiprows:跳过指定的行(可选参数),类型为:list-like, int, or callable
    • Rows to skip at the beginning, 1表示跳掉第一行。
  • nrows:指定读取的行数,通常用于较大的数据文件中。类型int, 默认是None,读取全部数据
  • converters:对指定列进行指定函数的处理,传入参数为列名与函数组成的字典,和usecols参数连用。
    • key 可以是列名或者列的序号,values是函数,可以自定义的函数或者Python的匿名lambda函数

应用举例:

# sheet_name演示,
import pandas as pd
df1 = pd.read_excel(r".\study\test_excel.xlsx", sheet_name=None)
print(df1)
df2 = pd.read_excel(r".\study\test_excel.xlsx")
print(df2)
df3 = pd.read_excel(r".\study\test_excel.xlsx", sheet_name=[0,"vegetables"])
print(df3)
{'student':   name  age sex address  score
0   刘一   18   女      上海    100
1   花二   40   男      上海     99
2   张三   25   男      北京     80
3   李四   30   男      西安     40
4   王五   70   男      青岛     70
5   孙六   65   女      泰州     90, 'vegetables':    序号          菜名   单价  产地
0   1     spinach  4.5  崇明
1   2    cucumber  5.0  奉贤
2   3      tomato  6.0  惠南
3   4  green bean  8.0  金山}
  name  age sex address  score
0   刘一   18   女      上海    100
1   花二   40   男      上海     99
2   张三   25   男      北京     80
3   李四   30   男      西安     40
4   王五   70   男      青岛     70
5   孙六   65   女      泰州     90
{0:   name  age sex address  score
0   刘一   18   女      上海    100
1   花二   40   男      上海     99
2   张三   25   男      北京     80
3   李四   30   男      西安     40
4   王五   70   男      青岛     70
5   孙六   65   女      泰州     90, 'vegetables':    序号          菜名   单价  产地
0   1     spinach  4.5  崇明
1   2    cucumber  5.0  奉贤
2   3      tomato  6.0  惠南
3   4  green bean  8.0  金山}

# header and names演示
import pandas as pd
df1 = pd.read_excel(r".\study\test_excel.xlsx", header=[0,1])
print(df1)
df2 = pd.read_excel(r".\study\test_excel.xlsx", header=None)
print(df2)
df3 = pd.read_excel(r".\study\test_excel.xlsx", names=["a", "b", "c", "d", "e"])
print(df3)
  name age sex address score
    刘一  18   女      上海   100
0   花二  40   男      上海    99
1   张三  25   男      北京    80
2   李四  30   男      西安    40
3   王五  70   男      青岛    70
4   孙六  65   女      泰州    90
      0    1    2        3      4
0  name  age  sex  address  score
1    刘一   18    女       上海    100
2    花二   40    男       上海     99
3    张三   25    男       北京     80
4    李四   30    男       西安     40
5    王五   70    男       青岛     70
6    孙六   65    女       泰州     90
    a   b  c   d    e
0  刘一  18  女  上海  100
1  花二  40  男  上海   99
2  张三  25  男  北京   80
3  李四  30  男  西安   40
4  王五  70  男  青岛   70
5  孙六  65  女  泰州   90

# index_col and usecols演示
import pandas as pd
df1 = pd.read_excel(r".\study\test_excel.xlsx", index_col=[0])  #以第一列作为行索引
print("1---------\n", df1)
print("2---------\n",df1["score"])  #score列的数据返回DataFrame,行索引已经变成了原来第一列的内容
print("3---------\n",df1.loc[["刘一", "李四"], "address"])

df4 = pd.read_excel(r".\study\test_excel.xlsx", usecols=[0,2])
print("4---------\n",df4)

df5 = pd.read_excel(r".\study\test_excel.xlsx", usecols="A:C,E")
print("5---------\n",df5)

df6 = pd.read_excel(r".\study\test_excel.xlsx", usecols=[0,1,2,3], skiprows=[1,2])
print("6---------\n",df6)

df7 = pd.read_excel(r".\study\test_excel.xlsx", usecols=[0,3], nrows=2)
print("7---------\n",df7)
1---------
       age sex address  score
name                        
刘一     18   女      上海    100
花二     40   男      上海     99
张三     25   男      北京     80
李四     30   男      西安     40
王五     70   男      青岛     70
孙六     65   女      泰州     90
2---------
 name
刘一    100
花二     99
张三     80
李四     40
王五     70
孙六     90
Name: score, dtype: int64
3---------
 name
刘一    上海
李四    西安
Name: address, dtype: object
4---------
   name sex
0   刘一   女
1   花二   男
2   张三   男
3   李四   男
4   王五   男
5   孙六   女
5---------
   name  age sex  score
0   刘一   18   女    100
1   花二   40   男     99
2   张三   25   男     80
3   李四   30   男     40
4   王五   70   男     70
5   孙六   65   女     90
6---------
   name  age sex address
0   张三   25   男      北京
1   李四   30   男      西安
2   王五   70   男      青岛
3   孙六   65   女      泰州
7---------
   name address
0   刘一      上海
1   花二      上海

# dtype演示
df1 = pd.read_excel(r".\study\test_excel.xlsx", names=["a", "b", "c", "d", "e"], 
                    dtype={"b": "float64", "e":"float64"}) #注意原数据的a,e列类型变化
print(df1)
    a     b  c   d      e
0  刘一  18.0  女  上海  100.0
1  花二  40.0  男  上海   99.0
2  张三  25.0  男  北京   80.0
3  李四  30.0  男  西安   40.0
4  王五  70.0  男  青岛   70.0
5  孙六  65.0  女  泰州   90.0
# converters演示
df1 = pd.read_excel(r".\study\test_excel.xlsx", usecols=[0,2,4],  # 1-name  3-sex 数值为原索引号
              converters={0:lambda x: x+"同学",  # 0代表上面[0,2,4]中的0,1.对应原2,2对应原4
                          1:lambda x: x + "孩子",
                          2:lambda x: x + 1000
                         })
print(df1)
   name  sex  score
0  刘一同学  女孩子   1100
1  花二同学  男孩子   1099
2  张三同学  男孩子   1080
3  李四同学  男孩子   1040
4  王五同学  男孩子   1070
5  孙六同学  女孩子   1090
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值