将专用列从数据帧转换为 Numpy 数组并正确循环



我有一个数据框...

            A  B  C  D  E  F
0  2018-02-01  2  3  4  5  6
1  2018-02-02  6  7  8  4  2
2  2018-02-03  3  4  5  6  7

。我将其转换为数字数组...

[['2018-02-01' 2 3 4 5 6]
 ['2018-02-02' 6 7 8 4 2]
 ['2018-02-03' 3 4 5 6 7]]

我想做的是:

  1. 在 numpy 数组中仅存储列 A、B 和 C,而不是所有列。
  2. 我想遍历第一列,然后是第二列和第三列。我怎样才能做到这一点?

我的代码如下:

import pandas as pd
df = pd.DataFrame([
 ['2018-02-01', 1, 3, 6, 102, 8],
['2018-02-01', 2, 3, 4, 5, 6],
['2018-02-02', 6, 7, 8, 4, 2],
['2018-02-03', 3, 4, 5, 6, 7]
], columns=['A', 'B', 'C', 'D', 'E', 'F'])
print(df)
#--> Here only save Columns A,B,C    
nparray = df.as_matrix()
print(nparray)
#--> Loop throug Columns and would like to have it looped over the Column A first
for i in nparray:
    print(i)
#Using the Values in B and C columns for that loop
calc= [func(B,C)
      for B, C in zip(nparray)]

更新:我做了一个数字例子。

            A  B  C  D    E  F
0  2018-02-01  1  3  6  102  8
1  2018-02-01  2  3  4    5  6
2  2018-02-02  6  7  8    4  2
3  2018-02-03  3  4  5    6  7

虚拟代码看起来类似于以下内容(它更像是一个嵌套循环(

loop over date 2018-02-01:
calc = func(Column B + Column C) = 1+3 = 4
next row is the same date so:
calc += func(Column B + Column C) = 4 + 2+ 3 = 9
for date 2018-02-01 the result is 9 and can be stored e.g. in a csv file
loop over date 2018-02-02
calc = func(Column B + Column C) = 6+7 = 13
for date 2018-02-02 the result is 13 and can be stored e.g. in a csv file
loop over date 2018-02-03
calc = func(Column B + Column C) = 3+4 = 7
for date 2018-02-03 the result is 7 and can be stored e.g. in a csv file

  1. df[['A','B','C']].values
  2. df[['B', 'C']].apply(func, axis=1)

在这里,func一次将接收一行,因此您可以按以下方式定义它:

def func(x):
    x.B *= 2
    x.C += 1
    return x

您也可以这样做:

calc = [func(B,C) for B, C in df[['B', 'C']].itertuples(index=False)]

或者这个:

calc = [func(x.B, x.C) for x in df.itertuples()]

请注意,这种迭代代码,无论是使用 itertuples 还是 apply 与其他"矢量化"方法相比,速度非常慢。 但是如果你坚持使用循环,你可以,对于小数据,这是可以的。

对于问题的第一部分,只需选择要使用的列:

print df[['A', 'B', 'C']].as_matrix()
>>>
[['2018-02-01' 2L 3L]
 ['2018-02-02' 6L 7L]
 ['2018-02-03' 3L 4L]]

问题的第二部分是多余的,与数据帧相比,遍历 numpy 数组之间没有区别,因为各个数据类型将是相同的,在本例中为整数。

因此使用:

for k in df.A:
    print k

最新更新