【问题标题】:How to split a string list into multiple lists in Python如何在 Python 中将字符串列表拆分为多个列表
【发布时间】:2021-02-15 03:36:28
【问题描述】:

我有以下清单:

x=['2 5 6 7', '9 11 13 15', '31 52 56 94']

我的最终目标是在 jupyter notebook 中将其显示为包含列和行的表格。

这是我到目前为止所做的:

  1. 我将列表转换为列表列表,现在我的列表如下所示:

    x=[['2 5 6 7'], ['9 11 13 15'], ['31 52 56 94']]

  2. 问题是我不知道如何拆分每个字符串。例如我想做得到:

    [['2' '5' '6' '7'], ['9' '11' '13' '15'], ['31' '52' '56' '94']]

以便我可以使用以下内容通过 pandas 库打印表格

import pandas as pd
df = pd.DataFrame (x,columns=['int1','int2','int3','int4'])
print (df)

最终输出应该是这样的,列名和行名

int1 int2 int3 int4
   2    5    6    7
   9   11   13   15
  31   52   56   94

请帮助我朝着正确的方向前进。

【问题讨论】:

    标签: python-3.x pandas strsplit


    【解决方案1】:

    试试:

    x=['2 5 6 7', '9 11 13 15', '31 52 56 94']
    pd.DataFrame([s.split() for s in x], columns=['int1', 'int2', 'int3', 'int4'])
    

    它给出:

      int1 int2 int3 int4
    0    2    5    6    7
    1    9   11   13   15
    2   31   52   56   94
    

    【讨论】:

    • 非常感谢。从过去的 3 个小时开始,我一直被困在这个问题上。
    猜你喜欢
    • 2022-11-25
    • 1970-01-01
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    相关资源
    最近更新 更多