为了账号安全,请及时绑定邮箱和手机立即绑定

在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 关注
  • 174 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信