python - 表格字符串数据转换为 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.
我已经使用pandas
andStringIO
将其转换为 adataframe
但df.columns
give的输出,['PID TTY', 'TIME CMD']
这不是我想要的。
如果逻辑与 python 相关而不是 pandas 会更好
解决方案
用于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')
推荐阅读
- r - 在R条形图/箱形图中标记每个类别:`gap.axis`等效?
- php - Wordpress 仅显示附有实践的实践类别
- python - 根据 Airflow 中任务的输出创建不同的 DAG
- jenkins - 使用 List Groovy 中的 collectEntries 创建并行阶段 Map
- vscode-settings - VSCode 可以在 windows 7 上很好地调试代码吗?
- javascript - 如何在三个js中将对象放入画布内
- python - 检查数据框中是否存在具有正确值的行,如果不存在则追加
- php - 致命错误:未捕获的错误:调用 view-thread.php:46 中字符串上的成员函数 fetch_array() 堆栈跟踪:第 46 行抛出 #0 {main}
- c++ - 最终链接失败:设备 collect2.exe 上没有剩余空间:错误:ld 返回 1 退出状态
- mysql - 无法连接到在 WSL2 中运行的 MySQL 服务器