如何将大量行和列从 .xlsx 输出保存到文件中

huangapple go评论56阅读模式
英文:

How to save large set of rows and columns from .xlsx output in a file

问题

你可以尝试使用以下代码将所有的行和列完整保存到.csv.txt文件中:

import pandas as pd

def foo():
    data = pd.read_excel('file/path/filename.xlsx')
    print(data)

    data.to_csv('Output.csv', index=False)  # 保存为CSV文件,不包括索引列
    data.to_csv('Output.txt', sep='\t', index=False)  # 保存为文本文件,使用制表符分隔,不包括索引列

这将把所有的行和列保存到相应的文件中,而不仅仅是前50行。

英文:

I have a .xlsx file with large set of rows and columns, and I would like to save the desired output in .csv or .txt file.

import pandas as pd
 
def foo():
    data = pd.read_excel('file/path/filename.xlsx')
    print(data)

    f = open('Output.txt', 'w')
    print(data.head(50),file = f)
    f.close()

I get the Output.txt as

Col1 Col2 ... Col99
1     1   ... 2
2     4   ... 3
.     .   ... .  
.     .   ... . 
4     2   ... 3

instead of all the rows and columns. I realize that I'm just saving whats been printed on screen, can anyone suggest how to save such columns and rows completely in a .csv or .txt?

答案1

得分: 3

data.to_csv('path_to_csv')

Did you try this already?

import pandas as pd
 
def foo():
    data = pd.read_excel('file/path/filename.xlsx')
    data.to_csv('path_to_csv', index=False)
英文:
data.to_csv('path_to_csv')

Did you try this already?

import pandas as pd
 
def foo():
    data = pd.read_excel('file/path/filename.xlsx')
    data.to_csv('path_to_csv', index=False)

答案2

得分: 1

以下是要翻译的内容:

看起来你想要 to_string(默认情况下会将你的 DataFrame 的每一部分打印出来):

def foo():
    data = pd.read_excel('file.xlsx')
    # print(data)

    with open('Output.txt', 'w') as f:
        data.head(50).to_string(f, index=False)
英文:

Looks like you want to_string (which by default prints every piece of your DataFrame as it is):

def foo():
    data = pd.read_excel('file.xlsx')
    # print(data)

    with open('Output.txt', 'w') as f:
        data.head(50).to_string(f, index=False)

huangapple
  • 本文由 发表于 2023年5月26日 16:10:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76338880.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定