Создать фрейм данных из фрейма данных - PullRequest
0 голосов
/ 07 августа 2020

Здравствуйте, у меня проблема c проблема, я работаю с большим CSV (в среднем 600x1000, файлы, которые создаются программным обеспечением, к которому у меня нет доступа, и, к сожалению, некоторые из них имеют неправильный формат:

enter image description here

dirt issue is when i use load the file with this code :

df=read_csv(csv_path,sep=';')

both cells circled in red are considered as column names so what i've done now is :

df=read_csv(csv_path,sep=';',names=None)

it worked exactly as i expected to ! But now here is my real problem i need to transpose this data frame and add real column names so here is my code :

df=read_csv(csv_path,sep=';',names=None)
col_names =["src_label"]
for i in range(len(df.columns)-1):
    col_names.append("Result_"+str(i))
df=df.transpose()
data=df.to_dict
df1 = DataFrame(data, columns=col_names)

However i get the following error :

ValueError: DataFrame constructor not properly called!

i've tried to call with

df1 = DataFrame(df, columns=col_names)

i also tried

df.columns=col_names

after having transposed it obviously but i has no effects and i also tried df.names=col_names i got a warning saying 'can't set new values by creating an attribute'

and last try was :

for j in range(len(col_names)-1):
    df = df.rename_axis(col_names[i], axis=i)

no errors but no effects either

EDIT : just tried to read csv like this :

df=read_csv(csv_path,sep=';',header=None)

and got

ParserError: Error tokenizing data. C error: Expected 2 fields in line 2, saw 975

To help me, i need a solution to create a fresh dataframe from the previous one and then adding the column names or dirctly add column names in the first datarame in order to get the following result : введите описание изображения здесь

Ответы [ 2 ]

0 голосов
/ 07 августа 2020

Я полагаю, вы не знаете, "поврежден" ли входной файл.

Чтобы справиться с этим, определите следующий класс, выполняющий настраиваемую фильтрацию вашего входного файла:

class InFile:
    def __init__(self, infile):
        self.infile = open(infile)

    def __iter__(self):
        return self

    def read(self, *args, **kwargs):
        while True:
            line = self.infile.readline()
            if not line:  # EOF
                self.infile.close()
                break
            if line.count(',') > 1:
                break
        return line

Он «проглатывает» строки с одной запятой или без нее.

Затем прочтите ваш CSV-файл:

df = pd.read_csv(InFile('Input.csv'))

Я тестировал приведенный выше код на:

  • «обычный» CSV-файл,
  • «поврежденный» файл с 00: 00: 00,500 в первой строке.

В обоих случаях я получил правильный DataFrame.

0 голосов
/ 07 августа 2020

Только что нашел решение:

df=read_csv(csv_path,sep=';',header=None,skiprows=[0])
df1=df.transpose()
col_names =["src_label"]
for i in range(len(df1.columns)-1):
    col_names.append("Result_"+str(i))
df1.columns=col_names

благодаря @HenryYik, который поставил меня на след skiprows

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...