超詳細! 生成DataFrame、讀取和保存各種格式數(shù)據(jù)
一、生成DataFrame
import pandas as pd
datas = {
'排名': [1, 2, 3, 4, 5],
'綜合得分': [894, 603, 589, 570, 569],
'粉絲數(shù)': [309147, 93704, 98757, 124712, 59847],
'獲贊數(shù)': [12200, 31637, 4987, 1736, 8996]
}
df = pd.DataFrame(datas)
df
結(jié)果如下:
datas1 = [
{'排名': 1, '綜合得分': 894, '粉絲數(shù)': 309147, '獲贊數(shù)': 12200},
{'排名': 2, '綜合得分': 603, '粉絲數(shù)': 93704, '獲贊數(shù)': 31637},
{'排名': 3, '綜合得分': 589, '粉絲數(shù)': 98757, '獲贊數(shù)': 4987},
{'排名': 4, '綜合得分': 570, '粉絲數(shù)': 124712, '獲贊數(shù)': 1736},
{'排名': 5, '綜合得分': 569, '粉絲數(shù)': 59847, '獲贊數(shù)': 8996}
]
df1 = pd.DataFrame(datas1)
df1
結(jié)果如下:
在爬取數(shù)據(jù)時,保存數(shù)據(jù)如果用pandas,需要組織數(shù)據(jù)生成DataFrame,以上兩種方法是很常用的,熟練掌握這兩種方法在保存爬取下來的數(shù)據(jù)時很有幫助。
二、讀取數(shù)據(jù)
# 讀取 Excel 數(shù)據(jù)
df2 = pd.read_excel('rank_datas.xlsx')
# 隨機抽取5行數(shù)據(jù)
df2.sample(5)
# 讀取 csv 數(shù)據(jù)
df3 = pd.read_csv('job_info.csv')
# 隨機抽取5行數(shù)據(jù)
df3.sample(5)


# 讀取 html 數(shù)據(jù)
df4 = pd.read_html('aliyun-ddns.html')[0]
# 隨機抽取5行數(shù)據(jù)
df4.sample(5)
結(jié)果如下:
pd.read_html( )這個方法雖然少用,但它的功能非常強大,有時可以用做爬蟲,直接抓取網(wǎng)頁 Table 表格型數(shù)據(jù),得到DataFrame。
# 讀取 json 數(shù)據(jù)
df5 = pd.read_json('fake_useragent.json')
df5.head()


三、保存數(shù)據(jù)

結(jié)果如下:

df.to_excel( ):保存到 Excel







點擊下方閱讀原文加入社區(qū)會員
評論
圖片
表情
