【问题标题】:Converting a Nested List to a Pandas Dataframe [duplicate]将嵌套列表转换为 Pandas 数据框 [重复]
【发布时间】:2019-09-15 00:18:29
【问题描述】:

尝试将 python 列表转换为 pandas 数据框:

input:
list = [[a,x,[1,2]],[a,y,[1]],[a,z,[1,2,3]],[b,v,[1]],[b,w,[1,2]]...]

一些转换技巧会导致:

output:
c1 c2 c3
 a  x  1
 a  x  2
 a  y  1
 a  z  1
 a  z  2
 a  z  3
 b  v  1
 b  w  1
 b  w  2

每个列表元素的第一个和第二个元素始终是单个值(成为 c1 和 c2),但第三个元素是一个可变长度的列表。我尝试了各种循环来转换为列表,每个元素都准备好作为“行”,但我无法使其工作。它有点像反向数据透视表,但这也对我没有帮助。任何帮助表示赞赏

【问题讨论】:

    标签: python pandas list dataframe nested


    【解决方案1】:
    enter code here
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame([['a','x',[1,2]],['a','y',[1]],['a','z',[1,2,3]],['b','v',[1]],['b','w',[1,2]]],columns=["colum1","column2","column3"])
    
    print(df)
    
    print("******************")
    
    
    
    
    lst_col = 'column3'
    
    r = pd.DataFrame({
      col:np.repeat(df[col].values, df[lst_col].str.len())
      for col in df.columns.drop(lst_col)}
    ).assign(**{lst_col:np.concatenate(df[lst_col].values)})[df.columns]
    print(r)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-22
      • 2017-03-21
      • 2020-12-16
      • 1970-01-01
      • 2020-03-31
      • 1970-01-01
      • 2018-04-17
      相关资源
      最近更新 更多