首页 > 解决方案 > 将不同类型的列表转换为 DataFrame

问题描述

希望转换此列表:

[[Chain(exchange='ABC', Id=123, Class='c1', expirations={'20180726', '20180830'}, strikes={1.1, 1.2})],
 [Chain(exchange='ABC', Id=345, Class='c2', expirations={'20180726', '20180830'}, strikes={0.5, 3.1, 2.8})]]

进入数据框:

exchange     Id      Class    expirations    strikes
 --------    --      -----    -----------    -------
 ABC         123      c1      20180726       1.1
 ABC         123      c1      20180726       1.2

 ...

 ABC         345      c2      20180830       2.8

链条是...

class Chain(builtins.tuple)
     |  Chain(exchange, Id, Class, expirations, strikes) 

是否可以使用列表理解和展平?

标签: pythonpandas

解决方案


在您的问题中,缺少某些部分。然而,我尝试了一段时间,我产生了这个有点混乱的代码。

对不起!

class Chain():    
    def __init__(self, exchange, Id, Class, expirations, strikes):
        self.exchange, self.Id, self.Class, self.expirations, self.strikes = exchange, Id, Class, expirations, strikes
        self.expirations = list(self.expirations)
        self.strikes = list(self.strikes)
    def merge(self):
        self.temp_list = []
        for index_1 in range(len(self.expirations)):
            for index_2 in range(len(self.strikes)):
                self.temp_list.append([self.exchange, self.Id, self.Class, 
    self.expirations[index_1], self.strikes[index_2]])
        return self.temp_list

    chain_1 = Chain(exchange='ABC', Id=123, Class='c1', expirations={'20180726', '20180830'}, strikes={1.1, 1.2}).merge()
    chain_2 = Chain(exchange='ABC', Id=345, Class='c2', expirations={'20180726', '20180830'}, strikes={0.5, 3.1, 2.8}).merge()

import pandas as pd
df = pd.DataFrame(chain_1+chain_2, columns=["exchange", "Id", "Class", "expirations", "strikes"])
df

Output:
exchange    Id  Class   expirations strikes
0   ABC     123     c1  20180726    1.1
1   ABC     123     c1  20180726    1.2
2   ABC     123     c1  20180830    1.1
3   ABC     123     c1  20180830    1.2
4   ABC     345     c2  20180726    0.5
5   ABC     345     c2  20180726    2.8
6   ABC     345     c2  20180726    3.1
7   ABC     345     c2  20180830    0.5
8   ABC     345     c2  20180830    2.8
9   ABC     345     c2  20180830    3.1

我希望这有帮助!采洪


推荐阅读