使用numpy将带有标头的列表列表转换为csv

时间:2018-12-09 10:55:23

标签: python csv numpy

我有一个列表列表,其中也包含标题。标头与所有列表都不匹配,并且并非所有列表都具有相同的计数。像这样:

interface Bar extends Foo {}

我想将其转换为CSV,并将所有标头值填充为空白,并将缺少的标头值填充为“ N / A”

像这样:

[
[['Row', '1'], ['header1', '1.23'], ['header2','5.67'], ['header3','6.55']],
[['Row', '2'], ['header2','19.67'], ['header3','9.55']],
[['Row', '3'], ['header2','19.67'], ['header3','9.55'], ['header4','16.88']]
]

我想知道如何去做

1 个答案:

答案 0 :(得分:1)

您可以将数据结构转换成词典列表。然后,您可以使用pandas.DataFrame.from_records

import pandas as pd

data = [
[['Row', '1'], ['header1', '1.23'], ['header2','5.67'], ['header3','6.55']],
[['Row', '2'], ['header2','19.67'], ['header3','9.55']],
[['Row', '3'], ['header2','19.67'], ['header3','9.55'], ['header4','16.88']]
]

df = pd.DataFrame.from_records(map(dict, data)).set_index("Row").fillna("N/A")
#     header1 header2 header3 header4
# Row                                
# 1      1.23    5.67    6.55     N/A
# 2       N/A   19.67    9.55     N/A
# 3       N/A   19.67    9.55   16.88
df.to_csv("file.csv")