Python 将具有不同类型的列表列表转换为数据帧
要转换此列表,请执行以下操作:Python 将具有不同类型的列表列表转换为数据帧,python,pandas,Python,Pandas,要转换此列表,请执行以下操作: [[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
[[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)
是否可以使用列表理解和展开功能?在您的问题中,某些部分缺失。然而,我尝试了一会儿,我产生了一个有点混乱的代码 对不起
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
我希望这有帮助!
Ceyhun是否可以将
链的构造函数添加到问题中?对不起,我尝试运行列表的代码,但没有成功。Thx@Ceyhun。链在一个大的列表中,所以我不能把它们作为链1…n。此外,过期和终止是“set”类型,类和交换是“str”类型,Id是“int”。实际上,我想为Chain类创建一个迭代器,但我无法实现。如果您用更多信息描述或显示Chain类,这将非常有用。我期待着看到答案。