逐行从数据帧读取数据

时间:2019-07-31 20:43:51

标签: python-3.x pandas

我需要一个不接受任何输入并返回一个代表从数据帧中提取的下一行数据的列表的功能的帮助

我尝试了一些迭代器,但是这种方法要求我有一个输入参数

def get_next_data_as_list():
    out = list(data.iloc[i])
    i= i + 1
    return out

get_next_data_as_list()

Example output: [1619.5, 1620.0, 1621.0, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, 1.0, 10.0,
     24.0, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, 1615.0, 1614.0, 1613.0, 1612.0, 1611.0, 1610.0,
     1607.0, 1606.0, 1605.0, 1604.0, 1603.0, 1602.0, 1601.5, 1601.0, 1600.0, 7.0, 10.0, 1.0, 10.0, 20.0, 3.0, 20.0,
     27.0, 11.0, 14.0, 35.0, 10.0, 1.0, 10.0, 13.0]

2 个答案:

答案 0 :(得分:1)

非常感谢MichaelD。我意识到当调用该函数时,生成器会重置。实际上,我可以通过创建一个初始化函数来修复它,该函数返回生成器并将其分配给变量。

```
def get_next_data_as_list_init():
    for i in range(len(data)):
        yield list(data.iloc[i])

x = get_next_data_as_list_init()
```

然后是主要功能;

```
def get_next_data_as_list():
    return x.__next__()
```

仅调用下一批。非常感谢MichaelD!

答案 1 :(得分:0)

执行此操作的一种方法是将函数视为生成器:

In [42]: df = pd.DataFrame({'x1':np.random.randn(5), 'x2':np.random.randn(5)})

In [43]: df
Out[43]:
         x1        x2
0  0.891725  0.653889
1  2.260866 -1.521131
2  0.453874  1.416261
3 -0.821557  0.586106
4  1.042644  0.556396

In [44]: def get_next_data_as_list():
    ...:     for i in range(len(df)):
    ...:         yield list(df.iloc[i])
    ...:

In [45]: for x in get_next_data_as_list():
    ...:     print(x)
    ...:
[0.8917247724868814, 0.6538894234684837]
[2.2608656845849993, -1.521131045383185]
[0.4538742078414329, 1.416260697660083]
[-0.8215569227294447, 0.5861059443795276]
[1.0426436741732399, 0.5563956233997533]

更明确地说:

In [46]: x = get_next_data_as_list()
In [47]: x.__next__()
Out[47]: [0.8917247724868814, 0.6538894234684837]

In [48]: x.__next__()
Out[49]: [2.2608656845849993, -1.521131045383185]