您的位置:首页 > 其它

数据分析之Pandas-05数据加载

2017-10-31 20:34 295 查看

01-读取文本格式数据

pandas提供了一些用于将表格型数据读取为DataFrame对象的函数

02-最常用

read_csv:从文件中加载带分隔符的数据,默认分隔符为逗号

read_table:从文件中加载带分隔符的数据,默认分隔符为制表符

03-读取数据库数据

导包
import pandas as pd
import sqlite3

读取数据
con = sqlite3.connect("../data/weather_2012.sqlite")
df = pd.read_sql("SELECT * from weather_2012 LIMIT 3", con)
df

设置index_col
df = pd.read_sql("SELECT * from weather_2012 LIMIT 3", con, index_col='id')
df

写数据
weather_df = pd.read_csv('../data/weather_2012.csv')
con = sqlite3.connect("../data/test_db.sqlite")
con.execute("DROP TABLE IF EXISTS weather_2017")
weather_df.to_sql("weather_2017", con)


04-读取网络数据

url = 'https://raw.githubusercontent.com/datasets/investor-flow-of-funds-us/master/data/weekly.csv'
pd.read_csv(url)


05-什么是数据透视表

数据透视表(Pivot Table)是一种交互式的表,可以进行某些计算,如求和与计数等。所进行的计算与数据跟数据透视表中的排列有关。

之所以称为数据透视表,是因为可以动态地改变它们的版面布置,以便按照不同方式分析数据,也可以重新安排行号、列标和页字段。每一次改变版面布置时,数据透视表会立即按照新的布置重新计算数据。另外,如果原始数据发生更改,则可以更新数据透视表。

06-透视表和交叉表

透视表

行分组透视表
df = DataFrame({'size':np.random.randn(4),
'height':np.random.randn(4),
'weight':np.random.randn(4),
'smoke':['No','Yes','No','Yes'],
'sex':['male','female','female','male']})
df2 = df.pivot_table(index = ['smoke'])

列分组透视表
df = DataFrame({'size':np.random.randn(4),
'height':np.random.randn(4),
'weight':np.random.randn(4),
'smoke':['No','Yes','No','Yes'],
'sex':['male','female','male','female']})
df2 = df.pivot_table(columns = ['smoke'])

行列分组透视表
df = DataFrame({'size':np.random.randn(4),
'height':np.random.randint(10,size = 4),
'weight':np.random.randn(4),
'smoke':['No','Yes','No','Yes'],
'sex':['male','female','female','female']})

df2 = df.pivot_table(index = 'sex',columns = 'smoke',aggfunc= sum,fill_value=0)
display(df,df2)

交叉表
df = DataFrame({'gender':['male','female','female','male','male','female','female','female','male','female'],
'hand':['left','right','right','right','right','right','left','right','right','right']})
display(df,pd.crosstab(df.gender,df.hand,margins=True))

数据:
hand            left        right       All
gender
female          1           5               6
male            1           3               4
All             2           8               10


07-数据获取地址

https://www.data.gov/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: