繁体   English   中英

循环通过 Pandas dataframe 作为二维数组

[英]Looping through a Pandas dataframe as a two dimensional array

在运行过程中的某个时刻,我有两个数据框,其中包含来自各种采样分布的标准偏差值。 dfbest 将最小偏差保持为最佳。 dftmp 记录当前值.. 所以,第一次 dftmp 看起来像这样

       0         1          2         3         4
0  22.552408  7.299163  15.114379  5.214829  9.124144

使用 dftmp.shape (1, 5)

暂时忽略pythonic构造并将数据帧视为2d arrays 就像VBA excel中的电子表格我写...

A:

if dfbest.empty:
    dfbest = dftmp
else:
    for R in range( dfbest.shape[0]):
       for C in range( dfbest.shape[1]):             
          if dfbest[R][C] > dftmp[R][C]:
             dfbest[R][C] = dftmp[R][C]

乙:

if dfbest.empty:
    dfbest = dftmp
else:
    for R in range( dfbest.shape[0]):
       for C in range( dfbest.shape[1]):
          if dfbest[C][R] > dftmp[C][R]:
             dfbest[C][R] = dftmp[C][R]

代码 A 失败,而 B 工作。 我希望相反,但我是 python 的新手,所以谁知道我在这里没有看到什么。有什么建议吗? 我怀疑有一个更合适的.iloc 解决方案。

当您像这样( dfbest[x][y] )访问 dataframe 时, x表示一列,然后y表示一行。 这就是代码 B 起作用的原因。

这里有更多信息: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#basics

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM