在Python3上使用Pandas对齐数据框

时间:2018-11-11 11:09:38

标签: python pandas

我有一个data,我正尝试将其存储在pandas dataFrame中。但是,它以一种奇怪的方式出现。我知道我做错了

有人可以帮助我找出问题所在吗?

代码

root@optstra:~# cat pandas_1.py
import pandas as pd
import numpy as np

numberOfRows = 1

SYMBOL = 'ABB'
volume_increasing = True
price_increase = True
OI_CHANGE = True
closedAboveYesterday = False
Above_22SMA = False

data_frame = pd.DataFrame(index=np.arange(0, numberOfRows), columns=('SYMBOL','Volume', 'Price', 'OI','OHLC','22SMA') )

for x in range(0,numberOfRows):
    data_frame.loc[x] = [{SYMBOL,volume_increasing,price_increase,OI_CHANGE,closedAboveYesterday,Above_22SMA} for n in range(6)]

print(data_frame)

输出

root@optstra:~# python3 pandas_1.py
               SYMBOL              Volume               Price                  OI                OHLC               22SMA
0  {False, True, ABB}  {False, True, ABB}  {False, True, ABB}  {False, True, ABB}  {False, True, ABB}  {False, True, ABB}

如果我按如下所述更改将数据写入数据帧的行

for x in range(0,numberOfRows):
    data_frame.loc[x] = [(SYMBOL,volume_increasing,price_increase,OI_CHANGE,closedAboveYesterday,Above_22SMA) for n in range(6)]

输出更改为

root@optstra:~# python3 pandas_1.py
                                  SYMBOL                  ...                                                    22SMA
0  (ABB, True, True, True, False, False)                  ...                    (ABB, True, True, True, False, False)

3 个答案:

答案 0 :(得分:2)

您为什么不尝试此操作-不确定是否正是您要查找的内容,因为您已在编辑中删除了该部分:

for x in range(0,numberOfRows):
    data_frame.loc[x] = [SYMBOL,volume_increasing,price_increase,OI_CHANGE,closedAboveYesterday,Above_22SMA]

输出:

  SYMBOL Volume Price    OI   OHLC  22SMA
0    ABB   True  True  True  False  False

答案 1 :(得分:2)

Updating an empty frame (e.g. using loc one-row-at-a-time)效率低下。

因此,更好/更快的方法是在列表中附加DataFrame建设者:

data = []
for x in np.arange(numberOfRows):
    row = [SYMBOL,volume_increasing,price_increase,OI_CHANGE,closedAboveYesterday,Above_22SMA]
    data.append(row)

c = ('SYMBOL','Volume', 'Price', 'OI','OHLC','22SMA')
data_frame = pd.DataFrame(data, columns=c)

list comprehension alternative

data = [[SYMBOL,volume_increasing,price_increase,OI_CHANGE,closedAboveYesterday,Above_22SMA] for x in np.arange(numberOfRows)]

答案 2 :(得分:0)

在我看来,您没有为数据帧正确建立索引。您可以执行以下操作:

for x in range(0, numberOfRows):
    data_frame['SYMBOL'][x] = SYMBOL
    data_frame['Volume'][x] = volume_increasing
    data_frame['Price'][x] = price_increase
    data_frame['OI'][x] = OI_CHANGE
    data_frame['OHLC'][x] = closedAboveYesterday
    data_frame['22SMA'][x] = Above_22SMA

这将为您提供所需的输出,或者,您也可以使用字典并完全避免使用for循环:

columns = ['SYMBOL','Volume', 'Price', 'OI','OHLC','22SMA']
data = {'SYMBOL': 'AAB',
        'Volume': True,
        'Price': True,
        'OI': True,
        'OHLC': False,
        '22SMA': False}

data_frame = pd.DataFrame(data=data, index=np.arange(0, 1), columns=columns)