系統(tǒng):Windows 7
語言版本:Anaconda3-4.3.0.1-Windows-x86_64
編輯器:pycharm-community-2016.3.2
pandas:0.19.2
- 這個系列講講Python的科學(xué)計算及可視化
- 今天講講pandas模塊
- Dataframe的遍歷
Part 1:目標(biāo)
- pandas功能很強(qiáng)大,我們可以使用pandas直接讀取數(shù)據(jù)庫獲取一個Df,也可以直接讀取Excel獲取一個Df,等等
- 那么對于生成的Df想獲取其中每一個元素怎么實(shí)現(xiàn)呢?
- 本文就是實(shí)現(xiàn)對Df的遍歷循環(huán),獲取每一行每一列的內(nèi)容
結(jié)果如圖

2.png
Part 2:代碼
import pandas as pd
dict_1 = {"time": ["2019-11-02", "2019-11-03", "2019-11-04", "2019-11-05",
"2019-12-02", "2019-12-03", "2019-12-04", "2019-12-05"],
"pos": ["P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8"],
"value1": [0.5, 0.8, 1.0, 2, 3, 5, 6, 7]}
df_1 = pd.DataFrame(dict_1, columns=["time", "pos", "value1"])
df_1.set_index("pos", inplace=True)
print(df_1)
print("\n")
for index, row in df_1.iterrows():
print(index)
print(row["time"])
print(row["value1"])
print("\n")
代碼截圖

3.png
Part 3:部分代碼解讀
-
for index, row in df_1.iterrows():,其中index為行索引的值,row表示這一行的一個Series,通過type函數(shù)獲取其數(shù)據(jù)類型,如下圖所示 - 那么除了這種遍歷方式,還有其它嗎?答案肯定是有的
print(type(index))
print(type(row))

4.png
本文為原創(chuàng)作品,歡迎分享朋友圈
長按圖片識別二維碼,關(guān)注本公眾號
Python 優(yōu)雅 帥氣

12x0.8.jpg