Как преобразовать текстовый файл в фрейм данных (сначала словари)? - PullRequest
0 голосов
/ 18 декабря 2018

Я знаю, что это не возможно, но я все еще хочу задать следующие вопросы:

Мой текстовый файл выглядит следующим образом: четыре вопроса с ответами.enter image description here

Есть ли какие-либо изменения при переносе текстового файла в кадр данных?(вопросы в виде столбцов и ответы для строк) Это ожидаемый результат enter image description here

txtfile=StringIO("""1. How do you like this product?
I really don't like this product. It broke after 3-month use
2. Rate your purchasing experience from one to ten?  Will you refer the 
product to your friend?
from 1 to 10, I gave 2
3. What part do you like the most for this product?
The outlook of the product was good but the quality was low
4. Do you have any recommendations that can help us improve?
I don’t think so""")

Над текстом

1 Ответ

0 голосов
/ 18 декабря 2018

Как то так?

from io import StringIO
txtfile=StringIO("""1. How do you like this product?
Answer1
2. Rate your purchasing experience from one to ten?  Will you refer the product to your friend?
Answer2
3. What part do you like the most for this product?
Answer3
4. Do you have any recommendations that can help us improve?
Answer4""")

df = pd.read_csv(txtfile,header=None)

df['Answers'] = df[0].str.extract('Answer(\d)')

df = df.bfill()
df = df[~df[0].str.startswith('Answer')]
df.set_index(0).T

Обновление:

from io import StringIO
txtfile=StringIO("""1. How do you like this product?
Answer1
2. Rate your purchasing experience from one to ten?  Will you refer the product to your friend?
Answer2
3. What part do you like the most for this product?
Answer3
4. Do you have any recommendations that can help us improve?
Answer4""")

df = pd.read_csv(txtfile,header=None)

ans_dict={'Answer1':"I don't like this product", 'Answer2':'from 1 to 10, I gave 2', 'Answer3':'The outlook of the product was good but quality was low', 'Answer4':"I don't think so Hope it helps"}


df['Answers'] = df[df[0].str.startswith('Answer')]

df['Answers'] = df['Answers'].map(ans_dict)

df = df.bfill()
df = df[~df[0].str.startswith('Answer')]
df.set_index(0).T
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...