【问题标题】:Convert list of strings to python dictinoary [closed]将字符串列表转换为python字典[关闭]
【发布时间】:2022-01-03 20:43:05
【问题描述】:

我有这样的数据结构:

lst = ['name, age, sex, height, weight',
'underweight,overweight,normal',
'David, 22, M, 185, -,-,78',
'Lily, 18, F, 165,-,75,-',
..............................]

权重分为三列(列表中的第二行)。如何将其写入熊猫数据框。

我所做的是使用以下方法将列表写入数据框:

pd.DataFrame(lst)

但这不是完整的解决方案,它有更复杂的逻辑。

请帮帮我

【问题讨论】:

  • 这不是列表列表。它是一个字符串列表。
  • 编辑了问题。我试图将其转换为列表列表,并在编写问题时想到了这样做。

标签: python pandas list dataframe


【解决方案1】:

您期望的输出并不完全清楚,但您可以使用列表理解预处理您的数据:

lst2 = [list(map(str.strip, e.split(','))) for e in lst] # split on commas
pd.DataFrame(lst2[2:], columns=lst2[0][:-1]+lst2[1])     # use first 2 item to build header
                                                         # rest is data

输出:

    name age sex height underweight overweight normal
0  David  22   M    185           -          -     78
1   Lily  18   F    165           -         75      -
多索引

虽然可行,但我不推荐这样做,使用起来会困难得多:

lst2 = [list(map(str.strip, e.split(','))) for e in lst]
cols = pd.MultiIndex.from_arrays([lst2[0][:-1]+[lst2[0][-1]]*3,
                                  ['']*4+lst2[1]])
pd.DataFrame(lst2[2:], columns=cols)

输出:

    name age sex height      weight                  
                        underweight overweight normal
0  David  22   M    185           -          -     78
1   Lily  18   F    165           -         75      -

【讨论】:

  • 有没有办法在标题中添加标题,我的意思是三个子标题,即。体重过轻、超重和正常都应该体重不足。
  • @TranquilOshan 是的,(请参阅更新),但老实说,除了导出之外,这不是一个好主意。您的数据框将更难操作
猜你喜欢
  • 2018-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-24
  • 2016-12-05
相关资源
最近更新 更多