首页 > 解决方案 > 表格字符串数据转换为 python 数据

问题描述

我有一个这样的字符串

"""PID TTY          TIME CMD
      1 ?        00:00:01 systemd
      2 ?        00:00:00 kthreadd
      3 ?        00:00:00 rcu_gp
      4 ?        00:00:00 rcu_par_gp"""

现在我希望数据像这样我可以访问它就像data["PID"]会给我一样1,2,3,4 and so for other headers.

我已经使用pandasandStringIO将其转换为 adataframedf.columnsgive的输出,['PID TTY', 'TIME CMD']这不是我想要的。

如果逻辑与 python 相关而不是 pandas 会更好

标签: pythonpython-3.xpandaslist

解决方案


用于sep="\s+"按空格分隔:

from io import StringIO

temp="""PID TTY          TIME CMD
      1 ?        00:00:01 systemd
      2 ?        00:00:00 kthreadd
      3 ?        00:00:00 rcu_gp
      4 ?        00:00:00 rcu_par_gp"""
df = pd.read_csv(StringIO(temp), sep="\s+")
   
print (df)
   PID TTY      TIME         CMD
0    1   ?  00:00:01     systemd
1    2   ?  00:00:00    kthreadd
2    3   ?  00:00:00      rcu_gp
3    4   ?  00:00:00  rcu_par_gp

print (df.columns)
Index(['PID', 'TTY', 'TIME', 'CMD'], dtype='object')
    

推荐阅读