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

2024-04-26 22:49:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框。。。你知道吗

            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. 我想循环第一列,然后是第二列和第三列。我怎样才能做到这一点?你知道吗

我的代码如下:

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

等等


Tags: andtheinloopdffordateis
2条回答
  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

相关问题 更多 >