как открыть CSV в Python? - PullRequest
       25

как открыть CSV в Python?

0 голосов
/ 11 апреля 2019

У меня есть набор данных в следующем формате.

row_num; locale; day_of_week; hour_of_day; agent_id; entry_page; path_id_set; traffic_type; session_durantion; хиты
"988681; L6; понедельник; 17; 1; 2111; "31672; 0"; 6; 7037; \ N "" 988680; L2; четверг; 22; 10; 2113; "" 31965; 0 ""; 2; 49; 14 "" 988679;L4; суббота; 21; 2; 2100; "0; 78464"; 1; 1892; 14 "988678; L3; суббота; 19; 8; 2113; 51462; 6; 0; 1; \ N"

Я хочу, чтобы он был в следующем формате:

row_num locale day_of_week hour_of_day agent_id entry_page path_id_set traffic_type session_durantion хиты
988681 L6 понедельник 17 1 2111 31672 0 6 7037 N
988680 L2 четверг 22 10 2113 31965 0 2 49 14
988679 L4 суббота 21 2 2100 0 78464 1 1892 14
988678 L3 суббота 19 8 2113 51462 6 0 1 N

Я попытался с помощью следующего кода:

import pandas as pd

df = pd.read_csv("C:\Users\Rahhy\Desktop\trivago.csv", delimiter = ";")

Но я получаю сообщение об ошибке:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Ответы [ 2 ]

0 голосов
/ 11 апреля 2019
import pandas as pd
from io import StringIO

# Load the file to a string (prefix r (raw) to not use \ for escaping)
filename = r'c:\temp\x.csv'
with open(filename, 'r') as file:
    raw_file_content = file.read()

# Remove the quotes which break the CSV file
file_content_without_quotes = raw_file_content.replace('"','')

# Simulate a file with the corrected CSV content
simulated_file = StringIO(file_content_without_quotes)

# Get the CSV as a table with pandas
# Since the first field in each data row shall not be used for indexing we need to set index_col=False
csv_data = pd.read_csv(simulated_file, delimiter = ';', index_col=False)
print(csv_data['hits']) # print some column
csv_data

Поскольку имеется 11 полей данных и 10 заголовков, используются только первые 10 полей. Вам придется выяснить, что вы хотите сделать с последним (значения: \ N, 14)

Выход:

0    7037
1      49
2    1892
3       1

enter image description here

См. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html

0 голосов
/ 11 апреля 2019

Использование replace():

with open("data_test.csv", "r") as fileObj:
    contents = fileObj.read().replace(';',' ').replace('\\', '').replace('"', '')
print(contents)

OUTPUT

row_num locale day_of_week hour_of_day agent_id entry_page path_id_set traffic_type session_durantion hits
988681 L6 Monday 17 1 2111 31672 0 6 7037 N 988680 L2 Thursday 22 10 2113 31965 0 2 49 14 988679 L4 Saturday 21 2 2100 0 78464 1 1892 14 988678 L3 Saturday 19 8 2113 51462 6 0 1 N

EDIT :

Вы можете открыть файл, прочитать его содержимое, заменить ненужные символы. записать новое содержимое в файл и затем прочитать его через pd.read_csv:

with open("data_test.csv", "r") as fileObj:
    contents = fileObj.read().replace(';',' ').replace('\\', '').replace('"', '')
# print(contents)

with open("data_test.csv", "w+") as fileObj2:
    fileObj2.write(contents)

import pandas as pd
df = pd.read_csv(r"data_test.csv", index_col=False)
print(df)

OUTPUT

row_num locale day_of_week hour_of_day agent_id entry_page path_id_set traffic_type session_durantion hits
988681 L6 Monday 17 1 2111 31672 0 6 7037 N 988680 L2 Thursday 22 10 2113 31965 0 2 49 14 988679 L4 Saturday 21 2 2100 0 78464 1 1892 14 988678 L3 Saturday 19 8 2113 51462 6 0 1 N
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...