Python: Replace values while reading CSV file with pandas

gio

i've a txt file that contains something like this:

Struct{a,b,c}
Struct {d,f,z}

I'd like to read this file and have this output:

  0   1   2
0 a   b   c
1 d   f   z

I tried to run this code

import numpy as np
import pandas as pd
def conv(val, default_val=''):
    try:
         return (val)
    except ValueError:
         return default_val
x = pd.read_csv('/Users/me/Desktop/connector/connector.txt', sep=",", header=None, converters={'Struct': conv, '{': conv, '}': conv })
print(x)

but this is the output:

          0  1   2
0  Struct{x  y  z}
1  Struct{a  b  c}

can somebody tell me why it doesn't work?

MaxU

This isn't working because parameter converters expects a dict of functions for converting values in certain columns. Keys can either be integers or column labels. None of ['Struct','{','}'] is a column label.

In order to read this text file, you would need to preprocess it getting rid of 'Struct', '{', '}'. I.e. you will need to convert it to a proper CSV file.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Python: Replace values while reading CSV file

Python pandas error while reading and writing csv file

reading csv file into python pandas

KeyError while reading a CSV file in Python

Error while reading csv file using python

How to convert string values to integer values while reading a CSV file?

Reading values for CSV file using Python

UnicodeDecodeError when reading CSV file in Pandas with Python

Reading chunks of csv file in Python using pandas

Pandas reading a specific line in python with a csv file

Python: Pandas read csv: Downcasting while reading csv

Reading values in a csv file while deleting unwanted ones

How to drop a specific column of csv file while reading it using pandas?

Pandas read_csv reading floating values which are not present in the file

Python Pandas CSV - reading

python rstrip usage within loop while reading csv file

skip second row of dataframe while reading csv file in python

Error while reading a compressed csv file using Python2.7

Error while reading csv file and returning dataframe in python

how to add rows in while reading csv file in python

Missing first row while reading from file - Python Pandas

python reading csv and while break

Reading in csv file to pandas fails

Reading csv like file to pandas

Pandas Reading csv file with " in the data

Pandas is not Reading Entire .CSV File

python pandas not reading first column from csv file

Python: How to error protect reading a csv/xlsx file with pandas

Python3 - .replace() strings while writing to a CSV file