pandas 基础
一、文件的读取和写入
1、文件读取
pandas将表格型数据读取为DataFrame,其中最常用的是read_csv
,read_table
,read_excel
函数 | 说明 |
---|---|
read_csv | 默认分隔符为逗号 |
read_table | 默认分隔符为制表符 |
read_excel | 读取xls或xlsx文件 |
这些函数有一些常用的公共参数
header=None
: 表示第一列不作为列名,默认为Trueindex_col
: 指定某一列或某几列为索引usecols
:指定读取哪些列,默认全部读取parse_dates
:需要转化为时间的列nrows
:表示读取的数据行数
以前将列转换为时间都是用的to_datetime( )
, 不太了解读取的时候就可以转换了
试了一下之前的作业
cases_by_country = pd.read_csv('confirmed_cases_by_country.csv',usecols=[0,2,3],parse_dates=['date'])
cases_by_country.head()
# country date cases
# 0 Afghanistan 2020-01-22 0
# 1 Albania 2020-01-22 0
# 2 Algeria 2020-01-22 0
# 3 Andorra 2020-01-22 0
# 4 Antigua and Barbuda 2020-01-22 0
cases_by_country.dtypes
# country object
# date datetime64[ns]
# cases int64
# dtype: object
如果在同时有date和time属性的表格中,还可以进行更多操作。链接:转换时间序列
read_table 指定分隔符
在不指定分隔符的情况下, 也可以读出数据
pd.read_table('joyful-pandas/data/my_table_special_sep.txt')
# col1 |||| col2
# 0 TS |||| This is an apple.
# 1 GQ |||| My name is Bob.
# 2 WT |||| Well done!
# 3 PT |||| May I help you?
pd.read_table('joyful-pandas/data/my_table_special_sep.txt',sep=' \|\|\|\| ', engine='python') # 默认引擎是C,python可以更丰富
# col1 col2
# 0 TS This is an apple.
# 1 GQ My name is Bob.
# 2 WT Well done!
# 3 PT May I help you?
2、数据写入
使用to_csv
函数,我们可以将数据写入文件,该文件中以逗号分隔
df_csv.to_csv('data/my_csv_saved.csv', index=False)
df_excel.to_excel('data/my_excel_saved.xlsx', index=False)
pandas 中没有定义to_table
函数,但是to_csv
可以保存为txt文件,并且允许自定义分隔,常用制表符\t
分隔
二、常用基本函数
learn_pandas.csv
:记录了四所学校学生的体测个人信息,本章节只使用其中前七列数据
df = pd.read_csv('joyful-pandas/data/learn_pandas.csv')
df.columns
# Index(['School', 'Grade', 'Name', 'Gender', 'Height', 'Weight', 'Transfer',
# 'Test_Number', 'Test_Date', 'Time_Record'],
# dtype='object')
df = df[df.columns[:7]]
1、汇总函数
函数 | 描述 |
---|---|
head() | 返回表或者序列的前n行,n默认为5 |
tail() | 返回表或者序列的后n行,n默认为5 |
info() | 返回表的信息概况 |
describe() | 数值列对应的主要统计量 |
info、describe只能实现较少信息的展示,如果想要对一份数据集进行更全面的分析,推荐使用pandas-profiling包
2、特征统计函数
quantile 、count、idmax函数
df_demo.quantile(0.75)
# Height 167.5
# Weight 65.0
# Name: 0.75, dtype: float64