Python 使用str(df)后如何返回数据帧?
我想我在保存一个包含一堆熊猫数据帧的熊猫系列时把事情搞砸了。事实证明,每个数据帧都被保存,就好像我对它们调用了Python 使用str(df)后如何返回数据帧?,python,pandas,dataframe,Python,Pandas,Dataframe,我想我在保存一个包含一堆熊猫数据帧的熊猫系列时把事情搞砸了。事实证明,每个数据帧都被保存,就好像我对它们调用了df.to\u string() 根据我到目前为止的观察,我的字符串在某些地方有额外的间距,当数据帧有太多的列显示在同一行上时,也有额外的\ 以下是“更合适的数据帧: df = pd.DataFrame(columns=["really long name that goes on for a while", "another really long string", "c"]*6,
df.to\u string()
根据我到目前为止的观察,我的字符串在某些地方有额外的间距,当数据帧有太多的列显示在同一行上时,也有额外的\
以下是“更合适的数据帧:
df = pd.DataFrame(columns=["really long name that goes on for a while", "another really long string", "c"]*6,
data=[["some really long data",2,3]*6,[4,5,6]*6,[7,8,9]*6])
我拥有并希望转换为数据帧的字符串如下所示:
# str(df)
' really long name that goes on for a while another really long string c \\\n0 some really long data 2 3 \n1 4 5 6 \n2 7 8 9 \n\n really long name that goes on for a while another really long string c \\\n0 some really long data 2 3 \n1 4 5 6 \n2 7 8 9 \n\n really long name that goes on for a while another really long string c \\\n0 some really long data 2 3 \n1 4 5 6 \n2 7 8 9 \n\n really long name that goes on for a while another really long string c \\\n0 some really long data 2 3 \n1 4 5 6 \n2 7 8 9 \n\n really long name that goes on for a while another really long string c \\\n0 some really long data 2 3 \n1 4 5 6 \n2 7 8 9 \n\n really long name that goes on for a while another really long string c \n0 some really long data 2 3 \n1 4 5 6 \n2 7 8 9 '
如何将这样的字符串还原回数据帧
谢谢新答案
对于您新编辑的问题,我的最佳答案是使用到_csv
而不是到_string
,到_string
并不真正支持此用例以及到_csv
(我不知道如何避免您在与StringIO实例之间进行大量转换…)
我希望这次更新能有所帮助,我将保留我的旧答案以保持连续性
旧答案
在一个非常酷的扭曲中,这个答案也将帮助您读取StAdfExcel上数据粘贴输出的一般粘贴格式。考虑到我们可以从这样的字符串中读取<代码> df>代码>:
data = """ 0 20 30 40 50
1 5 NaN 3 5 NaN
2 2 3 4 NaN 4
3 6 1 3 1 NaN"""
import pandas as pd
from io import StringIO
data = StringIO(data)
df = pd.read_csv(data, sep="\\s+")
这将导致以下df:
您可以用相同的方法将的输出读取到\u string
:
pd.read_csv(StringIO(df.to_string()), sep="\\s+")
得到的df
是相同的。新答案
对于您新编辑的问题,我的最佳答案是使用到_csv
而不是到_string
,到_string
并不真正支持此用例以及到_csv
(我不知道如何避免您在与StringIO实例之间进行大量转换…)
我希望这次更新能有所帮助,我将保留我的旧答案以保持连续性
旧答案
在一个非常酷的扭曲中,这个答案也将帮助您读取StAdfExcel上数据粘贴输出的一般粘贴格式。考虑到我们可以从这样的字符串中读取<代码> df>代码>:
data = """ 0 20 30 40 50
1 5 NaN 3 5 NaN
2 2 3 4 NaN 4
3 6 1 3 1 NaN"""
import pandas as pd
from io import StringIO
data = StringIO(data)
df = pd.read_csv(data, sep="\\s+")
这将导致以下df:
您可以用相同的方法将的输出读取到\u string
:
pd.read_csv(StringIO(df.to_string()), sep="\\s+")
结果是相同的。试试这个。更新后包含自动计算行数的逻辑。基本上我提取了原始数据帧索引(行数)的最大值,它位于大字符串内 如果我们使用您给出的示例从转换为字符串的数据帧开始:
df = pd.DataFrame(columns=["really long name that goes on for a while", "another really long string", "c"]*6,
data=[["some really long data",2,3]*6,[4,5,6]*6,[7,8,9]*6])
string = str(df)
我的代码执行一些循环,因此,如果原始数据帧有数十万行,这种方法可能需要一段时间。尝试此方法。更新为包含自动计算行数的逻辑。基本上,我提取原始数据帧索引(行数)的最大值,它位于大字符串中 如果我们使用您给出的示例从转换为字符串的数据帧开始:
df = pd.DataFrame(columns=["really long name that goes on for a while", "another really long string", "c"]*6,
data=[["some really long data",2,3]*6,[4,5,6]*6,[7,8,9]*6])
string = str(df)
我的代码执行一些循环,因此,如果原始数据帧有数十万行,这种方法可能需要一段时间。因此,我不确定这个问题对任何人有多大帮助,但我编写了一个函数(和一个帮助器),尝试将错误存储为pd.Series中嵌套的数据帧的数据带回 以下是功能:
def insertNan(substring):
rows = substring.split('\n')
headers = re.sub(" \s+", " ", rows[0].replace("\\","").strip()).split(" ")
# The [2] below is a placeholder for the index. (Look in str(df), may appear like "\\\n1")
# Notice that if your tables get past 100 rows, 2 needs to be 3, or be determined otherwise.
boundaries = [0] + [2] + [rows[0].find(header)+len(header) for header in headers]
values = []
for i, row in enumerate(rows):
values.append(row)
# First row is just column headers. If no headers then don't use these functions
if i==0:
continue
for j, bound in enumerate(boundaries[:-1]):
value = row[bound:boundaries[j+1]].strip()
if not value:
newstring = list(values[i])
newstring[boundaries[j+1]-3:boundaries[j+1]] = "NaN"
values[i] = ''.join(newstring)
if " " in value:
start = values[i].find(value)
newvalue = re.sub(" \s+", " ", value)
values[i] = values[i][:start]+newvalue+values[i][start+len(value)]
return '\n'.join(values)
def from_string(string):
string = string.replace("\\", "")
chunks = [insertNan(i).strip() for i in string.split("\n\n")]
frames = [pd.read_csv(StringIO(chunk), sep=" \\s+", engine='python')
for chunk in chunks]
return pd.concat(frames, axis=1)
# Read file and loop through series. These two lines might have to be modified.
corrupted_results = pd.read_excel(fileio, squeeze=True)
results = [from_string(result for result in corrupted_results.values
这几乎让我回到了我开始的pd.系列(结果)
除了一些过长的文本条目被“…”
截断之外
总之,将数据保存为嵌套在pd.Series中的数据帧可能是个坏主意。我现在决定保存一个连接的数据帧,该数据帧是通过将数据帧与添加的“name”列连接而成的,该列允许我在以后需要时使用.groupby
进行分离
作为补充说明,如果pd.Series中保存的数据帧没有标题,那么我提供的函数可能无法工作,除非修改
特别感谢ColdSpeed、Charles Landau和JamesD,感谢他们的时间、帮助和善意!因此,我不确定这个问题对任何人有多大帮助,但我编写了一个函数(和一个助手)来尝试恢复我错误地存储在pd系列中的数据帧中的数据 以下是功能:
def insertNan(substring):
rows = substring.split('\n')
headers = re.sub(" \s+", " ", rows[0].replace("\\","").strip()).split(" ")
# The [2] below is a placeholder for the index. (Look in str(df), may appear like "\\\n1")
# Notice that if your tables get past 100 rows, 2 needs to be 3, or be determined otherwise.
boundaries = [0] + [2] + [rows[0].find(header)+len(header) for header in headers]
values = []
for i, row in enumerate(rows):
values.append(row)
# First row is just column headers. If no headers then don't use these functions
if i==0:
continue
for j, bound in enumerate(boundaries[:-1]):
value = row[bound:boundaries[j+1]].strip()
if not value:
newstring = list(values[i])
newstring[boundaries[j+1]-3:boundaries[j+1]] = "NaN"
values[i] = ''.join(newstring)
if " " in value:
start = values[i].find(value)
newvalue = re.sub(" \s+", " ", value)
values[i] = values[i][:start]+newvalue+values[i][start+len(value)]
return '\n'.join(values)
def from_string(string):
string = string.replace("\\", "")
chunks = [insertNan(i).strip() for i in string.split("\n\n")]
frames = [pd.read_csv(StringIO(chunk), sep=" \\s+", engine='python')
for chunk in chunks]
return pd.concat(frames, axis=1)
# Read file and loop through series. These two lines might have to be modified.
corrupted_results = pd.read_excel(fileio, squeeze=True)
results = [from_string(result for result in corrupted_results.values
这几乎让我回到了我开始的pd.系列(结果)
除了一些过长的文本条目被“…”
截断之外
总之,将数据保存为嵌套在pd.Series中的数据帧可能是个坏主意。我现在决定保存一个连接的数据帧,该数据帧是通过将数据帧与添加的“name”列连接而成的,该列允许我在以后需要时使用.groupby
进行分离
作为补充说明,如果pd.Series中保存的数据帧没有标题,那么我提供的函数可能无法工作,除非修改
特别感谢ColdSpeed、Charles Landau和JamesD,感谢他们的时间、帮助和善良!@ColdSpeed事实上,当我尝试
读取我的字符串时,我遇到了一个解析错误。更新了问题,Thanks@coldspeed事实上,当我尝试对我拥有的字符串进行读取\u csv
时,我遇到了一个ParseError。更新了问题,谢谢。这项工作我完成了吗有包含空格的字符串吗?我当前的问题是我有一堆字符串(不是数据帧),我希望恢复数据帧。str(df)
只是我的字符串的一个示例。很抱歉confuction@AsheKetchum字符串是如何分隔的?如果可以在数据中找到未替换的分隔符,那么期望使用ab似乎有点不合理