python - 将字符串转换为熊猫数据框
问题描述
import pandas as pd
from StringIO import StringIO
msg1 = '" feature1 feature2 UIN Comop YYYYMM Sales Month grain\\n0 212 212 F1230901 220ES 201202 212 2 F1230901220ES\\n"'
def result_trans(res_str):
print res_str
res_str = StringIO(res_str)
part_hist_df = pd.read_csv(res_str, sep="\s+")
return part_hist_df
print result_trans(msg1)
我需要将此字符串转换为熊猫数据框,如下所示。请有任何帮助。
feature1 feature2 UIN Comop YYYYMM Sales Month grain
212 212 F1230901 220ES 201202 212 2 F1230901220ES
解决方案
IIUC,使用pd.read_table
msg1 = '" feature1 feature2 UIN Comop YYYYMM Sales Month grain\n0 212 212 F1230901 220ES 201202 212 2 F1230901220ES\\n"'
pd.read_table(sio(msg1.strip('""').replace('\\n','\n')), delim_whitespace=True)
如果数据只是字符串,则无需strip
pd.read_table(io.StringIO(msg1), delim_whitespace=True)
推荐阅读
- scheme - 这段代码的每一行发生了什么?
- c# - 使用 Polly 重试拦截器不适用于 Unity
- r - R:“相同”的令人惊讶的行为
- postgresql - 获取错误:尝试使用 golang-migrate 迁移到 postgres 数据库时无法获取锁
- python - 窗口未在外部 url 链接上打开新窗口或选项卡单击
- javascript - 使用 ajax/php 具有文件树视图的单页应用程序
- sql-server - 如何在批处理文件中获取用户输入并在我们的 sql server 代码中使用该值?
- laravel-5 - Laravel Google api 客户端获取刷新令牌并上传文件
- tensorflow - 如何从 tf.estimator.Estimator 中获取 tensorflow 会话?
- python - 在opencv SGBM中,当我使名为numDisparities的参数变大时,为什么视差图的左侧变暗?