чтение неструктурированного файла TXT в фрейм данных - PullRequest
0 голосов
/ 24 сентября 2019

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

с open (fname) как f: content = f.read (). splitlines ()

2019-09-26 14:15:44 discount=1e
019-09-26 14:16:44 discount=4e
019-09-26 14:17:44 discount=2e
019-09-26 14:18:44 discount=3e
019-09-26 14:19:44 discount=2e
some text
some text
some text 
Products: sold = 5, bought = 5, left = 0 (20% profit),
New data and new data in the same format

Ожидаемый фрейм данных

date                     discount    profit
2019-09-26 14:15:44         1          20%
2019-09-26 14:16:44         4          20%
2019-09-26 14:17:44         2          20%
2019-09-26 14:18:44         3          20%
2019-09-26 14:19:44         2          20%

1 Ответ

0 голосов
/ 24 сентября 2019

Это работает с вашими примерами данных, но вам может понадобиться настроить некоторые вещи с вашими реальными данными.

Данные:

2019-09-26 14:15:44 discount=1e
2019-09-26 14:16:44 discount=4e
2019-09-26 14:17:44 discount=2e
2019-09-26 14:18:44 discount=3e
2019-09-26 14:19:44 discount=2e
some text
some text
some text 
Products: sold = 5, bought = 5, left = 0 (20% profit),
2019-09-26 14:20:44 discount=1e
2019-09-26 14:21:44 discount=4e
2019-09-26 14:22:44 discount=2e
2019-09-26 14:23:44 discount=3e
2019-09-26 14:24:44 discount=2e
some text
some text
some text 
Products: sold = 5, bought = 5, left = 0 (15% profit)

In:

# range(12) because the expected input was 12 fields. May need to change this to the number of expected fields    
df = pd.read_clipboard(names=[x for x in range(12)]) 

# 10 is the column name with the profit.  May need to change this.
df[10] = df[10].bfill()

df['date'] = pd.to_datetime(df[0] +' '+ df[1], errors='coerce')
df = df[df['date'].notnull()]
df['discount'] = df[2].str.strip('discount=e')
df['profit'] = df[10].str.strip('()')

df[['date', 'discount', 'profit']]

Out:

|         date        | discount | profit |
|:-------------------:|----------|--------|
| 2019-09-26 14:15:44 | 1        | 20%    |
| 2019-09-26 14:16:44 | 4        | 20%    |
| 2019-09-26 14:17:44 | 2        | 20%    |
| 2019-09-26 14:18:44 | 3        | 20%    |
| 2019-09-26 14:19:44 | 2        | 20%    |
| 2019-09-26 14:20:44 | 1        | 15%    |
| 2019-09-26 14:21:44 | 4        | 15%    |
| 2019-09-26 14:22:44 | 2        | 15%    |
| 2019-09-26 14:23:44 | 3        | 15%    |
| 2019-09-26 14:24:44 | 2        | 15%    |
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...