简体   繁体   中英

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.

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM