简体   繁体   English

将零填充到 Python 列表

[英]Pad zeros to a Python list

I have a dataframe as follows:我有一个 dataframe 如下:

df=
year|text|value
2001|text1|10
2001|text2|11
2002|text2|12
2003|text3|56
2005|text8|8
2005|text1|23

Now,I want to make a list of lists from the dataframe as follows:现在,我想从 dataframe 中列出如下列表:

l1=[[[10,0,0,23],[0,12,0,0],[0,0,56,0],[0,0,0,8]],[text1,text2,text3,text8],[2001,2002,2003,2005]]

I want to add zeros in the list when there is no value for the text in a particular year.当特定年份的文本没有值时,我想在列表中添加零。

I have tried the following code:我尝试了以下代码:

for value in list(df['text'].values):
        df1=df[df['text']==value]
        series_list.append(list(df1['value'].values))
        names_list.append(value)
        year_list.append(list(df1['year'].values))  

I did not get the expected output.我没有得到预期的 output。 I initially tried to make 3 separate lists.我最初尝试制作 3 个单独的列表。

Convert the first two columns to a MultiIndex.将前两列转换为 MultiIndex。 Build a rectangular matrix by unstacking one level of the index.通过取消堆叠一级索引来构建一个矩形矩阵。 Extract the values and arrange them into a list.提取值并将它们排列到列表中。

matrix = df.set_index(['text', 'year']).unstack(fill_value=0)
matrix.values.tolist()
#[[10, 0, 0, 23], [11, 12, 0, 0], [0, 0, 56, 0], [0, 0, 0, 8]]

Add the index and the columns, if necessary:如有必要,添加索引和列:

matrix.values.tolist() + [matrix.index.tolist()] \
                       + [matrix.columns.levels[1].tolist()]
#[[10, 0, 0, 23], [11, 12, 0, 0], [0, 0, 56, 0], [0, 0, 0, 8],
# ['text1', 'text2', 'text3', 'text8'], [2001, 2002, 2003, 2005]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM