walid
walid

Reputation: 305

Extract data from a csv file

I have data like this form:

X=[]; 
X=[X,0.114]; 
X=[X,0.749]; 
X=[X,0.358]; 
    .
    .
    .

I want to extract the values in the lists in a single list, as:

X = [0.114, 0.749, 0.358,...]

I used this code but it doesn't work:

import pandas as pd
data = pd.read_csv('Xtest.txt')
count = data['X']

Could you please help me pull the values? And thank you.

Upvotes: 0

Views: 131

Answers (2)

E_K
E_K

Reputation: 2249

How about plain python? Something like

X = []
with open('Xtest.txt', 'r') as file:
    lines = file.readlines()
    for line in lines:
        try:
            X.append(float(line.split(',')[1].split(']')[0]))
        except Exception:
            continue
print(X)

Upvotes: 2

Dreamer12
Dreamer12

Reputation: 28

If 0.114, 0.749, 0.358,..are the values in column1 of the CSV file, the answer is as follows,

import pandas as pd
data = pd.read_csv('Xtest.txt')
y = data[0].to_list()
print(y)

Upvotes: 0

Related Questions