簡體   English   中英

如何從帶有注釋的 txt 文件創建 pandas dataframe?

[英]How to create a pandas dataframe from a txt file with comments?

我需要創建一個 pandas dataframe 基於 4 個帶有評論的 txt 文件(閱讀時跳過)基於以下結構:

# Moteur conçu par le Poly Propulsion Lab (PPL)
nom=Tondeuse

# Propriétés générales
hauteur=0.5
masse=20.0
prix=110.00

# Propriétés du moteur
impulsion specifique=80

# Moteur conçu par le Poly Propulsion Lab (PPL)
nom=Civic VTEC

# Propriétés générales
hauteur=2.0
masse=3000.0
prix=2968.00

# Propriétés du moteur
impulsion specifique=205

# Moteur conçu par le Poly Propulsion Lab (PPL)
nom=VelociRAPTOR

# Propriétés générales
hauteur=4.0
masse=2000.0
prix=6000.00

# Propriétés du moteur
impulsion specifique=250

# Moteur conçu par le Poly Propulsion Lab (PPL)
nom=La Puissance

# Propriétés générales
hauteur=12.0
masse=15000.0
prix=39000.00

# Propriétés du moteur
impulsion specifique=295

這就是我需要的結果:

            nom  hauteur    masse     prix  impulsion specifique
0      Tondeuse      0.5     20.0    110.0                    80
1    Civic VTEC      2.0   3000.0   2968.0                   205
2  VelociRAPTOR      4.0   2000.0   6000.0                   250
3  La Puissance     12.0  15000.0  39000.0                   295

我不知道這是否可能,但這就是我被要求做的

您的數據文件看起來非常接近配置文件。 您可以使用configparser從每個文件生成字典:

from pathlib import Path
from configparser import ConfigParser

data = []
for file in Path("data").glob("*.txt"):
    parser = ConfigParser()
    # INI file requires a section header. Yours don't have one.
    # So let's give it one called DEFAULT
    parser.read_string("[DEFAULT]\n" + file.read_text())
    data.append(dict(parser.items("DEFAULT")))

df = pd.DataFrame(data)

歡迎來到 Stackoverflow::)

如果您的 txt 文件具有您剛才顯示的內容,您可以使用 pandas 作為 CSV 文件讀取它們。

pandas.read_csv function 有很多東西可以幫助你:

  • 它輸出一個 dataframe,這是你想要結束的格式
  • 有一個comment輸入參數,您可以使用它定義要忽略的行
  • 您可以使用=號作為分隔符,這樣您就可以將數據拆分到所需的部分

現在,讓我們嘗試使用read_csv function 讀取您的文件之一:

import pandas as pd
df = pd.read_csv(file, comment='#', sep='=', header=None)
df
                    nom  Tondeuse                                                                                                                                                                                                                                               
0               hauteur       0.5                                                                                                                                                                                                                                               
1                 masse      20.0                                                                                                                                                                                                                                               
2                  prix     110.0                                                                                                                                                                                                                                               
3  impulsion specifique      80.0

我們還沒有完全做到這一點。 我們想要刪除沒有提供任何信息的索引列,並且我們想要轉置 dataframe(行 <-> 列)以便能夠將所有數據幀連接在一起。 我們開始做吧!

import pandas as pd
df = pd.read_csv(file, comment='#', sep='=', header=None, index_col=0).T
df

0       nom hauteur masse    prix impulsion specifique                                                                                                                                                                                                                          
1  Tondeuse     0.5  20.0  110.00                   80

這樣看起來好多了! 設置index_col=0使最左邊的列成為索引列,最后的.T轉置您的 dataframe。現在我們只需要將它放在一個循環中並從中制作一個完整的腳本!

import pandas as pd
import glob
import os

files = glob.glob(os.path.join(path, '*.csv'))

all_dfs = []
for file in files:
    current_df = pd.read_csv(file, comment='#', sep='=', header=None, index_col=0).T
    all_dfs.append(current_df)

total_df = pd.concat(all_dfs)
total_df

0           nom hauteur    masse      prix impulsion specifique                                                                                                                                                                                                                 
1  La Puissance    12.0  15000.0  39000.00                  295                                                                                                                                                                                                                 
1    Civic VTEC     2.0   3000.0   2968.00                  205                                                                                                                                                                                                                 
1  VelociRAPTOR     4.0   2000.0   6000.00                  250                                                                                                                                                                                                                 
1      Tondeuse     0.5     20.0    110.00                   80

請注意,您仍然有最左邊的帶有索引號的列,我沒有清除它,因為我不確定您在那里想要什么。

此外,重要的是,您需要注意,如果文件中列的名稱略有不同(例如impulsion specifiqueimpulsion spécifique ),這將帶來錯誤。 您將需要為這些創建錯誤處理程序。 或者可能強制執行某種模式,但這超出了這個問題的 scope。

我希望這有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM