先引入pandas库

import pandas as pd

使用read_csv()方法,读取整个.csv文件;

df = pd.read_csv(filepath_or_buffer=\'music.csv\')

read_csv()其他常用参数:

  • usecols:列表类型,默认None
    E.g. usecols=[1, 2, 3],取文件指定列,默认全部列
  • names:列表类型,默认None
    E.g. names=[‘size’, ‘category’],作为每一列的名字
  • dtype:字典类型,默认None
    E.g. dtype= {‘size’: int} ,将size转换为int类型
  • nrows: 读取文件前几行
    E.g. nrows=3,只去读文件前三行
#  head() 方法:取前几行数据,参数为空默认展示5行数据,可以传入其他数字。
#  tail() 方法:倒着从后读取后几行数据,用法同上。
df.head()

\"在这里插入图片描述\"
columns 方法:打印列名。

print(df.columns)

Index([\'歌单名\', \'作者\', \'播放次数\', \'创建时间\', \'标签\', \'URL\'], dtype=\' \')

shape 方法:打印数据的维度

print(df.shape)

(6866, 6)  #一共有6866行6列

取行数据

loc方法:读取行数据

# 打印第三行的数据
print(df.loc[3])

\"在这里插入图片描述\"

# 打印一至三行的数据,类似列表的切片操作
print(df.loc[1: 3])

# 打印1, 3, 5行的数据, 传入一个带有行号的列表
print(df.loc[[1, 3, 5]])

取列数据

通过列名取一列数据

df[playTimes]  或者 df.playTimes

通过多个列名取多列数据,传入一个含有多个列名的列表

df[[\'author\', \'playTimes\']]
收藏 打印