Python Pandas создает dataframe из файла с разделителями новой строки? - PullRequest
3 голосов
/ 20 марта 2019

У меня есть текстовый файл, который является расшифровкой с отметками времени, это выглядит так:

00:25
hold it miles lunch and remember I'm
00:30
working late tonight again man you're a
00:34
total slave to that business of yours
00:36
nobody's a slave to their own dream

Я пытаюсь выяснить, как импортировать его в Pandas Dataframe, чтобы он выглядел так:

[Time] [Text]
00:25  hold it miles lunch and remember I'm
00:30  working late tonight again man you're a
00:34  total slave to that business of yours
00:36  nobody's a slave to their own dream

Мне стыдно сказать, что я даже не знаю, с чего начать ... все методы, которые я знаю и пытались, дают следующее:

  row1  00:25
  row2  hold it miles lunch and remember I'm
  row3  00:30
  row4  working late tonight again man you're a
  row5  00:34
  row6  total slave to that business of yours
  row7  00:36
  row8  nobody's a slave to their own dream

Я нашел этот вопрос , и похоже, что это та же проблема, но я не могу сказать, как применить его при создании фрейма данных.

Спасибо за помощь!

Ответы [ 3 ]

4 голосов
/ 20 марта 2019

Вот метод для достижения этой цели:

# Import the sample data
data='''00:25
hold it miles lunch and remember I'm
00:30
working late tonight again man you're a
00:34
total slave to that business of yours
00:36
nobody's a slave to their own dream'''

# Create a list containing every line
data = data.split('\n')

# Parse the data, assigning every other row to a different column
col1 = [data[i] for i in range(0,len(data),2)]
col2 = [data[i] for i in range(1,len(data),2)]

# Create the data frame
df = pd.DataFrame({'Time': col1, 'Text': col2})
print(df)
    Time                                     Text
0  00:25     hold it miles lunch and remember I'm
1  00:30  working late tonight again man you're a
2  00:34    total slave to that business of yours
3  00:36      nobody's a slave to their own dream
2 голосов
/ 20 марта 2019

Еще один способ сделать это, разделив каждую строку и присвоив каждую вторую строку другому столбцу, например, Время и Текст.Наконец, сделайте это DataFrame из модифицированного словаря.

import pandas as pd

# Read your files here 
files = ['text.txt'] #  you can add file or bunch of files
data = {}
for f in files:
  with open (f, "r") as myfile:
    all_lines = myfile.read().splitlines() # split by line
    # assign every alternative line to Time and Text index alternatively
    data['Time'], data['Text'] = all_lines[::2],  all_lines[1::2]

# create dataframe from the dictionary
df = pd.DataFrame(data)
print(df)

Вывод:

    Time                                     Text
0  00:25     hold it miles lunch and remember I'm
1  00:30  working late tonight again man you're a
2  00:34    total slave to that business of yours
3  00:36      nobody's a slave to their own dream
2 голосов
/ 20 марта 2019

В качестве альтернативы (если столбец text не имеет :):

m=df.col.str.contains(":")
df_new=pd.concat([df[m].reset_index(drop=True),df[~m].reset_index(drop=True)],axis=1)
df_new.columns=['Time','Text']
print(df_new)

    Time                                     Text
0  00:25     hold it miles lunch and remember I'm
1  00:30  working late tonight again man you're a
2  00:34    total slave to that business of yours
3  00:36      nobody's a slave to their own dream
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...