在python中对齐列位置和相应的值

在python中对齐列位置和相应的值,python,pandas,loops,Python,Pandas,Loops,原始数据格式显示第1行为(1:20 3:25 5:24 9:20) 我正在尝试使用python或python中的任何其他方式将原始数据集转换为dataframe。 我将原始数据集分为两个列表:示例属性列表和示例值列表 sample_attribute [[1,3,5,9],[3,5,7,10],[1,4,8,10]] sample_value [[20,25,24,20],[16,20,24,21],[12,20,24,17] The perspective data frame should

原始数据格式显示第1行为(1:20 3:25 5:24 9:20)

我正在尝试使用python或python中的任何其他方式将原始数据集转换为dataframe。 我将原始数据集分为两个列表:示例属性列表和示例值列表

sample_attribute
[[1,3,5,9],[3,5,7,10],[1,4,8,10]]
sample_value
[[20,25,24,20],[16,20,24,21],[12,20,24,17]

The perspective data frame should look like

Column: 1  2  3  4  5  6 7  8  9  10 
row 1:  20 0  25 0  24 0 0  0  20  0
row 2:  0  0  16 0  20 0 24 0  0  21
row 3:  12 0  0  20  0 0  0 24 0  17


您的数据结构类似于字典。您可以将其转换为Python字典,然后使用pandas内置的from_dict方法:

import pandas as pd    

sample_attribute = [[1,3,5,9],[3,5,7,10],[1,4,8,10]]
sample_value = [[20,25,24,20],[16,20,24,21],[12,20,24,17]]

# store sample in list of dictionaries
sample = [dict(zip(keys, values)) for keys, values in zip(sample_attribute,sample_value)]

# create dataframe
df = pd.DataFrame(sample)

# add columns without values
df = df.reindex(range(df.columns.min(),df.columns.max()+1),axis=1)

# replace NAN with zero
df = df.fillna(0)