python - 将不同类型的列表转换为 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)
是否可以使用列表理解和展平?
解决方案
在您的问题中,缺少某些部分。然而,我尝试了一段时间,我产生了这个有点混乱的代码。
对不起!
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
我希望这有帮助!采洪
推荐阅读
- selenium - Docker - 不推荐使用 scale 命令。改用带有 --scale 标志的 up 命令
- haskell - 为什么我只需要旧 GHC 的 Data.Monoid.(<>)?
- php - 如何在大字符串中找到相似的文本?
- php - PHP 查找最高键值的索引
- delphi - 无法将变量添加到 FastReport Firemonkey frxReport 对象
- linux - git push 挂起来很奇怪
- ssl - Enterprise PKI mmc 中的 PKI 问题位置
- javascript - 缺少数据点的 RGraph
- python - 如何将管道分隔的字符串读入数据帧?
- talend - Talend - 不使用子作业的错误处理