亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在Python中將txt數據拆分為列

在Python中將txt數據拆分為列

蕭十郎 2023-07-18 17:44:26
我有一個以下格式的 .txt 數據集:01/01/2018 ['cat', 'bear', 'ant']01/02/2018 ['horse', 'wolf', 'elephant']01/03/2018 ['parrot', 'bird', 'fish]我想使用 PYTHON 并將其設置為以下格式的 2 列:  'Date'       'Animal'01/01/2018       cat01/01/2018       bear   01/01/2018       ant01/02/2018       horse01/02/2018       wolf01/02/2018       elephant01/03/2018       parrot01/03/2018       bird01/03/2018       fish(txt 文件實際上更長,但為了更好地理解而進行了簡化)。我不知道如何繼續:read_csv或open(但隨后它會像對象一樣讀取它)?我應該設置分隔符嗎?我嘗試了幾件事,但沒有任何作用。提前致謝
查看完整描述

1 回答

?
郎朗坤

TA貢獻1921條經驗 獲得超9個贊

使用 pandas 創建表:


import ast


import pandas as pd


dates = []

animals = []

lines = []


# Read file lines

with open('file.txt', 'r') as f:

    lines = f.readlines()


for l in lines:

    # Spliting date and animals

    date_string, animals_string = l.split(' ', maxsplit=1)

    # Safely evaluate animals list

    animals_list = ast.literal_eval(animals_string)

    # Duplicate date the amount of animals in that date

    dates.extend([date_string] * len(animals_list))

    # Append animals

    animals.extend(animals_list)


# Create dataframe for the dates and animals

df = pd.DataFrame({'Date': dates, 'Animal': animals})


# Print the dataframe

print(df)

輸出:


         Date    Animal

0  01/01/2018       cat

1  01/01/2018      bear

2  01/01/2018       ant

3  01/02/2018     horse

4  01/02/2018      wolf

5  01/02/2018  elephant

6  01/03/2018    parrot

7  01/03/2018      bird

8  01/03/2018      fish


查看完整回答
反對 回復 2023-07-18
  • 1 回答
  • 0 關注
  • 194 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號