系统:Windows 7
语言版本:Anaconda3-4.3.0.1-Windows-x86_64
编辑器:pycharm-community-2016.3.2
pandas:0.19.2
- 这个系列讲讲Python的科学计算及可视化
- 今天讲讲pandas模块
- Dataframe的遍历
Part 1:目标
- pandas功能很强大,我们可以使用pandas直接读取数据库获取一个Df,也可以直接读取Excel获取一个Df,等等
- 那么对于生成的Df想获取其中每一个元素怎么实现呢?
- 本文就是实现对Df的遍历循环,获取每一行每一列的内容
结果如图
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函数获取其数据类型,如下图所示 - 那么除了这种遍历方式,还有其它吗?答案肯定是有的
print(type(index))
print(type(row))
4.png
本文为原创作品,欢迎分享朋友圈
长按图片识别二维码,关注本公众号
Python 优雅 帅气
12x0.8.jpg