AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 77356073
Accepted
user366312
user366312
Asked: 2023-10-25 08:48:05 +0800 CST2023-10-25 08:48:05 +0800 CST 2023-10-25 08:48:05 +0800 CST

o quadro de dados não é empilhado verticalmente quando salvo

  • 772

dados1.dat

   1 ASN C  7.042   9.118  0.000 1 1 1 1  1  0
   2 LEU H  5.781   5.488  7.470 0 0 0 0  1  0
   3 THR H  5.399   5.166  6.452 0 0 0 0  0  0
   4 GLU H  5.373   4.852  6.069 0 0 0 0  1  0
   5 LEU H  5.423   5.164  6.197 0 0 0 0  2  0
   6 LYS H  5.247   4.943  6.434 0 0 0 0  1  0
   7 ASN C  5.485   8.103  8.264 0 0 0 0  1  0
   8 THR C  6.675   9.152  9.047 0 0 0 0  1  0
   9 PRO C  6.372   8.536 11.954 0 0 0 0  0  0
  10 VAL H  5.669   5.433  6.703 0 0 0 0  0  0
  11 SER H  5.304   4.924  6.407 0 0 0 0  0  0
  12 GLU H  5.461   5.007  6.088 0 0 0 0  1  0
  13 LEU H  5.265   5.057  6.410 0 0 0 0  3  0
  14 ILE H  5.379   5.026  6.206 0 0 0 0  1  0
  15 THR H  5.525   5.154  6.000 0 0 0 0  1  0
  16 LEU H  5.403   5.173  6.102 0 0 0 0  1  0
  17 GLY H  5.588   5.279  6.195 0 0 0 0  1  0
  18 GLU H  5.381   5.238  6.675 0 0 0 0  1  0
  19 ASN H  5.298   5.287  6.668 0 0 0 0  1  0
  20 MSE H  5.704   7.411  4.926 0 0 0 0  1  0

dados2.dat

  21 GLY C  5.978   9.254  9.454 0 0 0 0  1  0
  22 LEU C  6.778  10.534 12.640 0 0 1 2  2  0
  23 GLU C  7.187   7.217 10.728 0 0 0 0  2  0
  24 ASN C  5.392   8.296 10.702 0 0 0 0  0  0
  25 LEU C  5.657   6.064  9.609 0 0 0 1  3  0
  26 ALA C  5.446   5.528  7.503 0 0 0 0  2  0
  27 ARG C  5.656   8.071  8.419 0 0 0 0  0  0
  28 MSE C  6.890   9.157  8.728 0 0 0 0  1  0
  29 ARG C  6.330   7.993 11.562 0 0 0 0  0  0
  30 LYS H  5.428   5.207  5.897 0 0 0 0  1  0
  31 GLN H  5.402   5.046  6.349 0 0 0 0  1  0
  32 ASP H  5.426   5.093  6.226 0 0 0 1  1  0
  33 ILE H  5.361   5.004  6.194 0 0 0 0  6  0
  34 ILE H  5.443   5.150  6.190 0 0 0 0  5  0
  35 PHE H  5.403   5.181  6.293 0 0 0 0  1  0
  36 ALA H  5.533   5.357  6.193 0 0 0 0  3  0
  37 ILE H  5.634   5.167  6.025 0 0 0 1  5  0
  38 LEU H  5.402   5.121  6.104 0 0 0 0  3  0
  39 LYS H  5.470   5.092  6.101 0 0 0 0  1  0
  40 GLN H  5.491   5.210  6.054 0 0 0 0  2  0
import os
import pandas as pd
from src.utils.get_root_dir import get_root_directory

def save_dataframe_to_ascii(df, filepath):
    df.to_csv(filepath, sep=',', index=False)

def getDataFrame(dataDirectoryPathString: str) -> pd.DataFrame:
    dataframes = []
    for filename in os.listdir(dataDirectoryPathString):
        if filename.endswith('.dat'):
            filepath = os.path.join(dataDirectoryPathString, filename)
            df = pd.read_csv(filepath, sep='\t')
            dataframes.append(df)
    concatenated_df = pd.concat(dataframes, ignore_index=True)
    return concatenated_df


if __name__ == "__main__":
    dataFrame = getDataFrame(get_root_directory() + "/data/")
    save_dataframe_to_ascii(dataFrame, get_root_directory() + "/save/save.txt")

Saída:

   1 ASN C  7.042   9.118  0.000 1 1 1 1  1  0,  21 GLY C  5.978   9.254  9.454 0 0 0 0  1  0
   2 LEU H  5.781   5.488  7.470 0 0 0 0  1  0,
   3 THR H  5.399   5.166  6.452 0 0 0 0  0  0,
   4 GLU H  5.373   4.852  6.069 0 0 0 0  1  0,
   5 LEU H  5.423   5.164  6.197 0 0 0 0  2  0,
   6 LYS H  5.247   4.943  6.434 0 0 0 0  1  0,
   7 ASN C  5.485   8.103  8.264 0 0 0 0  1  0,
   8 THR C  6.675   9.152  9.047 0 0 0 0  1  0,
   9 PRO C  6.372   8.536 11.954 0 0 0 0  0  0,
  10 VAL H  5.669   5.433  6.703 0 0 0 0  0  0,
  11 SER H  5.304   4.924  6.407 0 0 0 0  0  0,
  12 GLU H  5.461   5.007  6.088 0 0 0 0  1  0,
  13 LEU H  5.265   5.057  6.410 0 0 0 0  3  0,
  14 ILE H  5.379   5.026  6.206 0 0 0 0  1  0,
  15 THR H  5.525   5.154  6.000 0 0 0 0  1  0,
  16 LEU H  5.403   5.173  6.102 0 0 0 0  1  0,
  17 GLY H  5.588   5.279  6.195 0 0 0 0  1  0,
  18 GLU H  5.381   5.238  6.675 0 0 0 0  1  0,
  19 ASN H  5.298   5.287  6.668 0 0 0 0  1  0,
  20 MSE H  5.704   7.411  4.926 0 0 0 0  1  0,
,  22 LEU C  6.778  10.534 12.640 0 0 1 2  2  0
,  23 GLU C  7.187   7.217 10.728 0 0 0 0  2  0
,  24 ASN C  5.392   8.296 10.702 0 0 0 0  0  0
,  25 LEU C  5.657   6.064  9.609 0 0 0 1  3  0
,  26 ALA C  5.446   5.528  7.503 0 0 0 0  2  0
,  27 ARG C  5.656   8.071  8.419 0 0 0 0  0  0
,  28 MSE C  6.890   9.157  8.728 0 0 0 0  1  0
,  29 ARG C  6.330   7.993 11.562 0 0 0 0  0  0
,  30 LYS H  5.428   5.207  5.897 0 0 0 0  1  0
,  31 GLN H  5.402   5.046  6.349 0 0 0 0  1  0
,  32 ASP H  5.426   5.093  6.226 0 0 0 1  1  0
,  33 ILE H  5.361   5.004  6.194 0 0 0 0  6  0
,  34 ILE H  5.443   5.150  6.190 0 0 0 0  5  0
,  35 PHE H  5.403   5.181  6.293 0 0 0 0  1  0
,  36 ALA H  5.533   5.357  6.193 0 0 0 0  3  0
,  37 ILE H  5.634   5.167  6.025 0 0 0 1  5  0
,  38 LEU H  5.402   5.121  6.104 0 0 0 0  3  0
,  39 LYS H  5.470   5.092  6.101 0 0 0 0  1  0
,  40 GLN H  5.491   5.210  6.054 0 0 0 0  2  0

As linhas deveriam ter sido empilhadas verticalmente.

Por que a saída está quebrada?

Como posso consertar isso?

python
  • 1 1 respostas
  • 39 Views

1 respostas

  • Voted
  1. Best Answer
    Zach Young
    2023-10-25T09:33:05+08:002023-10-25T09:33:05+08:00

    Se você não precisa usar o Pandas, e não vejo você usando-o para outra coisa senão concatenar (até agora), recomendo usar o módulo csv do Python para empilhar arquivos do tipo CSV - será mais rápido que o Pandas e use memória próxima a zero:

    import csv
    
    TAB = "\t"
    
    # Get files first, using maybe just use `glob.glob(get_root_directory()+'/data/*.dat')`
    dat_files = ["input1.dat", "input2.dat"]
    
    with open("output.dat", "w", newline="", encoding="utf-8") as f_out:
        writer = csv.writer(f_out, delimiter=TAB)
    
        for dat_file in dat_files:
            with open(dat_file, newline="", encoding="utf-8") as f_in:
                reader = csv.reader(f_in, delimiter=TAB)
    
                writer.writerows(reader)
    

    A readervariável é um iterador sobre todas as linhas do arquivo com o qual foi criada. A chamada writer.writerows(reader)fará com que cada linha do leitor seja iterada e entregue diretamente ao escritor para escrita. Essa abordagem também quase não usa memória, pois a linha apenas passa da entrada diretamente para a saída.

    Também mostro como obter os arquivos primeiro para evitar níveis extras de recuo/complexidade.

    Com os arquivos de amostra que você compartilhou (e convertendo qualquer número de espaços em uma TAB), meu output.dat se parece com:

    1   ASN C   7.042   9.118   0.000   1   1   1   1   1   0
    2   LEU H   5.781   5.488   7.470   0   0   0   0   1   0
    3   THR H   5.399   5.166   6.452   0   0   0   0   0   0
    ...
    38  LEU H   5.402   5.121   6.104   0   0   0   0   3   0
    39  LYS H   5.470   5.092   6.101   0   0   0   0   1   0
    40  GLN H   5.491   5.210   6.054   0   0   0   0   2   0
    
    • 1

relate perguntas

  • Como divido o loop for em 3 quadros de dados individuais?

  • Como verificar se todas as colunas flutuantes em um Pandas DataFrame são aproximadamente iguais ou próximas

  • Como funciona o "load_dataset", já que não está detectando arquivos de exemplo?

  • Por que a comparação de string pandas.eval() retorna False

  • Python tkinter/ ttkboostrap dateentry não funciona quando no estado somente leitura

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    destaque o código em HTML usando <font color="#xxx">

    • 2 respostas
  • Marko Smith

    Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}?

    • 1 respostas
  • Marko Smith

    Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)?

    • 2 respostas
  • Marko Smith

    Por que as compreensões de lista criam uma função internamente?

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Marko Smith

    java.lang.NoSuchMethodError: 'void org.openqa.selenium.remote.http.ClientConfig.<init>(java.net.URI, java.time.Duration, java.time.Duratio

    • 3 respostas
  • Marko Smith

    Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)?

    • 4 respostas
  • Marko Smith

    Por que o construtor de uma variável global não é chamado em uma biblioteca?

    • 1 respostas
  • Marko Smith

    Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto?

    • 1 respostas
  • Marko Smith

    Somente operações bit a bit para std::byte em C++ 17?

    • 1 respostas
  • Martin Hope
    fbrereto Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}? 2023-12-21 00:31:04 +0800 CST
  • Martin Hope
    比尔盖子 Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)? 2023-12-17 10:02:06 +0800 CST
  • Martin Hope
    Amir reza Riahi Por que as compreensões de lista criam uma função internamente? 2023-11-16 20:53:19 +0800 CST
  • Martin Hope
    Michael A formato fmt %H:%M:%S sem decimais 2023-11-11 01:13:05 +0800 CST
  • Martin Hope
    God I Hate Python std::views::filter do C++20 não filtrando a visualização corretamente 2023-08-27 18:40:35 +0800 CST
  • Martin Hope
    LiDa Cute Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)? 2023-08-24 20:46:59 +0800 CST
  • Martin Hope
    jabaa Por que o construtor de uma variável global não é chamado em uma biblioteca? 2023-08-18 07:15:20 +0800 CST
  • Martin Hope
    Panagiotis Syskakis Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto? 2023-08-17 21:24:06 +0800 CST
  • Martin Hope
    Alex Guteniev Por que os compiladores perdem a vetorização aqui? 2023-08-17 18:58:07 +0800 CST
  • Martin Hope
    wimalopaan Somente operações bit a bit para std::byte em C++ 17? 2023-08-17 17:13:58 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve