使用流式数据在数据帧中进行数据拆分

2024-09-28 01:24:34 发布

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

使用以下代码检索股票名称及其ltp

df=pd.DataFrame(data=None)

def on_ticks(ws, ticks):
    global df
    for sc in ticks:
        token=sc['instrument_token']
        name=trd_portfolio[token]['name']
        ltp=sc['last_price']
        df=df.append([name,ltp],ignore_index=True)

print(df)

然而,两个附加项,即名称和ltp都在同一列中提取,因此我无法进一步操作数据。相同的输出如下所示

              0
0     BANKBARODA
1          39.05
2     NATCOPHARM
3         574.55
4     AUROPHARMA
         ...
4249      194.15
4250     FRETAIL
4251        80.9
4252    HDFCLIFE
4253      517.95

[4254 rows x 1 columns]

请建议一种方法,以便我可以在两个不同的列中有名称和ltp,以便进一步工作


Tags: 代码name名称tokennonedataframedfdata
2条回答

使用双大括号:

df = df.append([[name, ltp]], ignore_index=True)
# creating a new dataframe with name and ltp values
# however, since the requirement is to have these within individual 
# columns and not rows, using transpose (T) to address it
df1 = pd.DataFrame([name,ltp]).T

# explicitly adding column names to the temp dataframe and the same will repeat
# everytime a new temp dataframe is formed. This will ensure that the new values
# get appended to the correct columns in the aggregated version
df1.columns = ['name', 'ltp']

# append the temp dataframe to the aggregated version to be published as final
df=df.append(df1,ignore_index=True)

相关问题 更多 >

    热门问题