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

时间:2018-02-01 13:50:45

标签: python arrays pandas numpy dataframe

我有一个数据框......

            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

...我将其转换为numpy数组...

[['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. 我想循环第一列,然后是第二列和第三列。我怎样才能做到这一点?
  3. 我的代码如下:

    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
    

2 个答案:

答案 0 :(得分:1)

  1. unchecked
  2. df[['A','B','C']].values
  3. 此处,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,这种迭代代码与其他"矢量化"相比都非常慢。方法。但是如果你坚持使用循环,你可以,对于小数据,它就没问题了。

答案 1 :(得分:0)

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

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