【问题标题】:Tabular String data convert to python data表格字符串数据转换为 python 数据
【发布时间】:2020-12-15 23:11:38
【问题描述】:

我有一个这样的字符串

"""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.

我使用pandasStringIO 将其转换为dataframe,但df.columns 的输出提供['PID TTY', 'TIME CMD'],这不是我想要的。

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

【问题讨论】:

  • 不,这是一个错误。以某种方式将其删除。

标签: python python-3.x pandas list


【解决方案1】:

使用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')
    

【讨论】:

    猜你喜欢
    • 2015-01-10
    • 1970-01-01
    • 2021-11-09
    • 2022-08-17
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    相关资源
    最近更新 更多