从数据帧(Python)内的字典中提取值

从数据帧(Python)内的字典中提取值,python,pandas,dataframe,Python,Pandas,Dataframe,正在尝试在数据帧中提取词典。但是不能。所提到的解决方案都不符合我的要求,因此也寻求同样的帮助 instrument_token last_price change depth 0 17600770 180.75 20.500000 {'buy': [{'quanti

正在尝试在数据帧中提取词典。但是不能。所提到的解决方案都不符合我的要求,因此也寻求同样的帮助

    instrument_token  last_price      change                                                                                          depth
0           17600770      180.75   20.500000  {'buy': [{'quantity': 1, 'price': 1, 'orders': 1},{'quantity': 0, 'price': 0.0, 'orders': 0}], 'sell': [{'quantity': 1, 'price': 1, 'orders': 1},{'quantity': 0, 'price': 0.0, 'orders': 0}]}
1           12615426        0.05  -50.000000  {'buy': [{'quantity': 2, 'price': 2, 'orders': 2},{'quantity': 0, 'price': 0.0, 'orders': 0}], 'sell': [{'quantity': 2, 'price': 2, 'orders': 2},{'quantity': 0, 'price': 0.0, 'orders': 0}]}
2           17543682        0.35  -89.062500  {'buy': [{'quantity': 3, 'price': 3, 'orders': 3},{'quantity': 0, 'price': 0.0, 'orders': 0}], 'sell': [{'quantity': 3, 'price': 3, 'orders': 3},{'quantity': 0, 'price': 0.0, 'orders': 0}]}
3           17565954        6.75  -10.000000  {'buy': [{'quantity': 4, 'price': 4, 'orders': 4},{'quantity': 0, 'price': 0.0, 'orders': 0}], 'sell': [{'quantity': 4, 'price': 4, 'orders': 4},{'quantity': 0, 'price': 0.0, 'orders': 0}]}
4           26077954        3.95  -14.130435  {'buy': [{'quantity': 5, 'price': 5, 'orders': 5},{'quantity': 0, 'price': 0.0, 'orders': 0}], 'sell': [{'quantity': 5, 'price': 5, 'orders': 5},{'quantity': 0, 'price': 0.0, 'orders': 0}]}
5           17599490      141.75   -2.241379  {'buy': [{'quantity': 6, 'price': 6, 'orders': 6},{'quantity': 0, 'price': 0.0, 'orders': 0}], 'sell': [{'quantity': 6, 'price': 6, 'orders': 6},{'quantity': 0, 'price': 0.0, 'orders': 0}]}
6           17566978       17.65   -1.671309  {'buy': [{'quantity': 7, 'price': 7, 'orders': 7},{'quantity': 0, 'price': 0.0, 'orders': 0}], 'sell': [{'quantity': 7, 'price': 7, 'orders': 7},{'quantity': 0, 'price': 0.0, 'orders': 0}]}
7          26075906       24.70  -16.554054  {'buy': [{'quantity': 8, 'price': 8, 'orders': 8},{'quantity': 0, 'price': 0.0, 'orders': 0}], 'sell': [{'quantity': 8, 'price': 8, 'orders': 8},{'quantity': 0, 'price': 0.0, 'orders': 0}]}
希望转换为以下内容:

    instrument_token  last_price      change    buy_price    sell_price
0           17600770      180.75   20.500000       1              1
1           12615426        0.05  -50.000000       2              2
2           17543682        0.35  -89.062500       3              3
3           17565954        6.75  -10.000000       4              4
4           26077954        3.95  -14.130435       5              5  
5           17599490      141.75   -2.241379       6              6
6           17566978       17.65   -1.671309       7              7
...
通过无法将字典转换为上述所需df中所示的所需df.col,可以使用for循环访问各个元素。

我在这里使用将其从字符串转换为python数据结构。对于实际的字典,就像您的情况一样,您可以从脚本中删除部分。
获取字典并合并回原始数据帧。根据您的输出,假设您只对每个子列表中的第一个dict感兴趣,分别进行购买和出售

import ast
res = [{f"{x}_price" : ast.literal_eval(ent)[x][0]['price'] 
        for x in ("buy","sell")} 
        for ent in df.pop('depth') ]

df.join(pd.DataFrame(res))

    instrument_token    last_price  change     buy_price    sell_price
0   17600770            180.75      20.500000       1          1
1   12615426            0.05       -50.000000       2          2
2   17543682            0.35       -89.062500       3          3
3   17565954            6.75       -10.000000       4          4
4   26077954            3.95       -14.130435       5          5
5   17599490            141.75     -2.241379        6          6
6   17566978            17.65      -1.671309        7          7
7   26075906            24.70      -16.554054       8          8
对于实际词典:

res = [{f"{x}_price" : ent[x][0]['price'] 
        for x in ("buy","sell")} 
        for ent in df.pop('depth') ]

#merge back to df
result = df.join(pd.DataFrame(res))

这就是你要找的吗

def get_prices(depth, tag):
    def sum(items):
        total = 0
        for item in items:
            total += item['price']
        return total
    return int(sum(depth[tag]))

df['buy_price'] = df['depth'].apply(lambda depth: get_prices(depth, 'buy'))
df['sell_price'] = df['depth'].apply(lambda depth: get_prices(depth, 'sell'))
df.drop(columns='depth', inplace=True)
print(df)
输出:

instrument_token  last_price     change  buy_price  sell_price
0          17600770      180.75  20.500000          1           1
1          12615426        0.05 -50.000000          2           2
2          17543682        0.35 -89.062500          3           3
3          17565954        6.75 -10.000000          4           4
4          26077954        3.95 -14.130435          5           5
5          17599490      141.75  -2.241379          6           6
6          17566978       17.65  -1.671309          7           7
7          26075906       24.70 -16.554054          8           8

您希望仅从列表的第一个元素获取
price
,而不是求和,然后执行以下操作:

df[“买入价格”]=df[“深度”].str[“买入”].str[0].str[“价格”]
df[“卖出价格”]=df[“深度”].str[“卖出”].str[0].str[“价格”]
如果希望获得所有嵌套元素的总和:

df[“买入价格”]=df[“深度”].str[“买入”].apply(lambda x:sum(el[“价格”]表示el in x))
df[“卖出价格”]=df[“深度”].str[“卖出”].apply(λx:sum(el[“价格”]表示el in x))