2017-04-01 17 views
1

我有一个关于写入数据帧的数据到一个文件中的两个问题:如何编写多dataframes到同一张纸上,而无需复制列标签

我的程序在数据帧的许多分组的行生成汇总统计,并保存到在完成时写入我的output.csv文件的StringIO缓冲区。我有一种感觉,pd.concat会更适合,但我无法得到它的工作。当我有机会时,我可以尝试添加一段代码,希望有人能够解释如何正确连接,我认为这将解决我的问题。

这就是说,我的程序工作,这是超过我可以要求。尽管如此,我最关心的是CSV文件如何最终为写入缓冲区的每个汇总统计数据帧重复使用相同的列标签,并顺便将它们复制到我的CSV文件中。有没有办法只写一次列标签并避免多个重复标签行?

我的第二个问题是关于写入Excel以跳过不必要的复制和粘贴。就像我以前的问题一样,这只是一个小小的障碍,但仍然让我感到不安,因为我想以正确的方式做事。问题是我想要将所有帧写入同一张表。为避免覆盖相同的数据,有必要使用缓冲区来存储数据直到结束。没有一个文档似乎对我的特殊情况有所帮助。我设计了一个解决方法:xlwt缓冲区 - > output.write(buffer.getvalue()) - > pd.to_csv(输出),然后通过pd.read_csv重新导入同一文件,最后添加另一个将数据框写入Excel的写入器。在完成所有这些工作后,我终于坚持使用CSV的简单性,因为Excel作家实际上放大了重复行的丑陋性。关于如何更好地处理我的缓冲区问题的任何建议,因为我更愿意将Excel编写器简化和控制为CSV输出。

对不起,没有任何上下文的代码。我厌倦了我最好的解释没有它。如有需要,我可以在有机会获得免费机会时添加代码。

+0

关于第二个问题,请参阅:http://stackoverflow.com/questions/32957441/putting-many-python-pandas -dataframes-to-one-excel-worksheet – bernie

+0

这对我不起作用,因为我需要首先初始化一个空白数据框,这是我不能做的。 – Maksim

+0

@Maksim你的问题是相当一般的,请包括代码,以便人们可以帮助你。 – splinter

回答

2

我同意连接数据帧可能是一个更好的解决方案。您应该可以针对某些示例代码/数据框专门提出问题。

对于第二个问题,您可以使用startrowstartcol参数将数据框放入Excel工作表中。您可以使用header布尔参数跳过重复标题,并且可以使用index布尔参数跳过索引。

例如:

import pandas as pd 


# Create some Pandas dataframes from some data. 
df1 = pd.DataFrame({'Data': [11, 12, 13, 14]}) 
df2 = pd.DataFrame({'Data': [21, 22, 23, 24]}) 
df3 = pd.DataFrame({'Data': [31, 32, 33, 34]}) 
df4 = pd.DataFrame({'Data': [41, 42, 43, 44]}) 

# Create a Pandas Excel writer using XlsxWriter as the engine. 
writer = pd.ExcelWriter('pandas_test.xlsx', engine='xlsxwriter') 

# Add the first dataframe to the worksheet. 
df1.to_excel(writer, sheet_name='Sheet1', index=False) 

offset = len(df1) + 1 # Add extra row for column header. 

# Add the other dataframes. 
for df in (df2, df3, df4): 
    # Write the datafram without a column header or index. 
    df.to_excel(writer, sheet_name='Sheet1', startrow=offset, 
       header=False, index=False) 

    offset += len(df) 

# Close the Pandas Excel writer and output the Excel file. 
writer.save() 

输出:

enter image description here

+0

谢谢!偏移线很简单但很精彩。 – Maksim

+0

这是我的问题到代码示例的第一部分:http://stackoverflow.com/questions/43170601/how-to-use-pd-concat-with-an-un-initiated-dataframe – Maksim

相关问题