![](/img/trans.png)
[英]How do I format my pandas dataframe through python to get columns in the csv output?
[英]How do I present my output as a Pandas dataframe?
CHECK_OUTPUT_HERE目前,我得到的 output 是字符串格式。 我不确定如何将该字符串转换为 pandas dataframe。 我的 output 中有 3 个不同的表。 它是字符串格式。 以下两种解决方案之一对我有用:
将该字符串 output 转换为 3 个不同的数据帧。 或更改 function 中的某些内容,以便我将 output 作为 3 个不同的数据帧。
我曾尝试使用 RegEx 将字符串 output 转换为 dataframe 但它不适用于我的情况,因为我希望我的 output 是动态的。 如果我提供另一个输入,它应该可以工作。
def column_ch(self, sample_count=10):
report = render("header.txt")
match_stats = []
match_sample = []
any_mismatch = False
for column in self.column_stats:
if not column["all_match"]:
any_mismatch = True
match_stats.append(
{
"Column": column["column"],
"{} dtype".format(self.df1_name): column["dtype1"],
"{} dtype".format(self.df2_name): column["dtype2"],
"# Unequal": column["unequal_cnt"],
"Max Diff": column["max_diff"],
"# Null Diff": column["null_diff"],
}
)
if column["unequal_cnt"] > 0:
match_sample.append(
self.sample_mismatch(column["column"], sample_count, for_display=True)
)
if any_mismatch:
for sample in match_sample:
report += sample.to_string()
report += "\n\n"
print("type is", type(report))
return report
由于您有一个字符串,您可以将您的字符串传递到类似文件的缓冲区中,然后使用pandas read_csv将其读取到 dataframe 中。
假设您的带有 dataframe 的字符串被称为dfstring
,代码将如下所示:
import io
bufdf = io.StringIO(dfstring)
df = pd.read_csv(bufdf, sep=???)
如果您的字符串包含多个数据帧,请使用 split 将其split
并使用循环。
import io
dflist = []
for sdf in dfstring.split('\n\n'): ##this seems the separator between two dataframes
bufdf = io.StringIO(sdf)
dflist.append(pd.read_csv(bufdf, sep=???))
小心传递适当的sep
参数,我的???
意味着我无法理解什么是合适的参数。 您的字段由空格分隔,因此您可以使用sep='\s+'
) 但我看到您也有空格,这不应该是分隔符,因此这可能会导致解析错误。 sep
接受正则表达式,因此要将 2 个连续的空格作为分隔符,您可以这样做: sep='\s\s+'
(这将需要一个额外的参数engine='python'
)。 但同样,请确保在两个连续字段之间至少有 2 个空格。
有关io
模块和StringIO
的参考,请参见此处。
请注意, io
模块存在于 python3 中,但不存在于 python2 中(它有另一个名称),但由于最新的 pandas 版本需要 python3,我猜你正在使用 python3。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.