第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

在Python中將txt數(shù)據(jù)拆分為列

在Python中將txt數(shù)據(jù)拆分為列

蕭十郎 2023-07-18 17:44:26
我有一個(gè)以下格式的 .txt 數(shù)據(jù)集:01/01/2018 ['cat', 'bear', 'ant']01/02/2018 ['horse', 'wolf', 'elephant']01/03/2018 ['parrot', 'bird', 'fish]我想使用 PYTHON 并將其設(shè)置為以下格式的 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 文件實(shí)際上更長(zhǎng),但為了更好地理解而進(jìn)行了簡(jiǎn)化)。我不知道如何繼續(xù):read_csv或open(但隨后它會(huì)像對(duì)象一樣讀取它)?我應(yīng)該設(shè)置分隔符嗎?我嘗試了幾件事,但沒(méi)有任何作用。提前致謝
查看完整描述

1 回答

?
郎朗坤

TA貢獻(xiàn)1921條經(jīng)驗(yàn) 獲得超9個(gè)贊

使用 pandas 創(chuàng)建表:


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


查看完整回答
反對(duì) 回復(fù) 2023-07-18
  • 1 回答
  • 0 關(guān)注
  • 193 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)