美文网首页python之路
Pandas构造DataFrame常用的几种方式

Pandas构造DataFrame常用的几种方式

作者: 非鱼2018 | 来源:发表于2020-05-17 21:57 被阅读0次

1.通过numpy数组,如:

import pandas as pd
import numpy as np
dates=pd.date_range('2020-05-01',periods=6)
x=np.ones([6,4], dtype = int)
df=pd.DataFrame(x,index=dates,columns=list('ABCD'))
df.head()

2.字典列表,即包含项为字典的列表,类似于行的形式构造

import pandas as pd
df1=pd.DataFrame([{"id":123,"name":456},{"id":222,"name":888}])
df1.head()

3.字典:字典,其中字典的值为列表,类似于列的形式

import pandas as pd
df1=pd.DataFrame({"id":[123,456,789],"name":['zhangsan','lisi','wangwu']})
df1.head()

4.读取csv以及记事本

df=pd.read_csv('123.csv')
读取记事本数据,需要指定分隔字符
df=pd.read_csv('123.txt',sep=‘:’)

5.读取excel
df=pd.read_excel('123.xlsx')
一次读取多个sheet

with pd.ExcelFile('demo1.xlsx') as file:
    df3=pd.read_excel(file,'Sheet1')
    df4=pd.read_excel(file,'Sheet2')
#写入多个sheet
with pd.ExcelWriter('demo1.xlsx') as writer:
    df.to_excel(writer, sheet_name='Sheet1')
    df2.to_excel(writer, sheet_name='Sheet2')

读取多个sheet到一个dataframe

import pandas as pd
df1=pd.read_excel('demo1.xlsx', sheet_name=None) 
df1

6.读取数据库

from pandas.io import sql
conn = sqlite3.connect('example.db')
query="select * from stocks"
results=sql.read_sql(query,con=conn)
results.head(5)

7.读取剪贴板,直接从剪贴板读取表格数据

hank=pd.read_clipboard()
hank.head()

8.读取html
df1=pd.read_html(url) #直接指定url,读取该静态页面的table,不存在table则会报错
如果是js框架生成的页面,可以使用无头浏览器+selenium,
df1=pd.read_html(driver.page_source) #table标记
这里的返回都是list,多个table,需要使用
df1[index]来得到dataframe
如果是非table标记的表格,则不适用,需要解析数据自己拼装生成dataframe

相关文章

网友评论

    本文标题:Pandas构造DataFrame常用的几种方式

    本文链接:https://www.haomeiwen.com/subject/apjdghtx.html