I am given a CSV file, the first column of which is the index, and the second column is the data which is separated by a space:
1. "1 2 3 4 5 6"
2. "6 5 4 3 2 1"
3. "2 4 6 8 10 12"
and so on.
I want to make a matrix out of the 2nd column which should look like this:
[ 1 2 3 4 5 6
6 5 4 3 2 1
2 4 6 8 10 12]
How can I do the same in python
one = [1,2,3]
two = ["1 2 3 4 5 6","6 5 4 3 2 1","2 4 6 8 10 12"]
nested=[val.split() for val in two]
res=[int(item) for sublist in nested for item in sublist]
print(res)
RESULT
[1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1, 2, 4, 6, 8, 10, 12]
I've split the list into nested list and then flatend the list.
You might want to use the pandas library :
import pandas
data = pandas.read_csv("file.csv", sep=",")
data = data.drop(data.columns[0], axis=1)
print(data)
Output:
1 2 3 4 5 6
6 5 4 3 2 1
2 4 6 8 10 12
Use pandas library to easily read and manipulate csv files
import pandas as pd
data = pd.read_csv("PATH_TO_FILE.csv", index_col=0,delimiter=" ",header=None)
for more information on read_csv from pandas
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html
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.