Home > other >  Converting a CSV column into a 1D list and then into a 2D list
Converting a CSV column into a 1D list and then into a 2D list

Time:07-29

Hope you are well,

I am fairly new in the python world and the coding world in general. I wanted to test python/panda's powers and the usefulness of making lists.

I have a column called 'Lines' in my csv file which reads like this:

Lines
A,B,C
A,D,C
B,C,D,E
A,B,C,D,E
C
C,D,E

Which I converted to a 1D list (thanks to pandas):

lines = df['Lines']
print(lines):
['A,B,C', 'A,D,C', 'B,C,D,E', 'A,B,C,D,E', 'C', 'C,D,E']

Now I know there are a ton of tutorials out there but somehow none worked for me... The output I am searching for would be something like this:

print(lines[0][1]):
B
print(lines[2][2]):
D

Is this something that is doable in python I wonder? Creating a 2D list based on multiple items in a specific CSV row? Thanks for any help/resource provided! Apologies in advance if the template provided is not useful/up-to-standards.

R.

CodePudding user response:

Given:

       Lines
0      A,B,C
1      A,D,C
2    B,C,D,E
3  A,B,C,D,E
4          C
5      C,D,E

Doing:

>>> df.Lines = df.Lines.str.split(',')
>>> print(df.Lines[0][1]):
B
>>> print(df.Lines[2][2]):
D

CodePudding user response:

You can do something like:

lines = pd.array([i.split(",") for i in df['Lines'])

lines is now a 2D array. You can access elements like you wanted to.

>>> lines[0][1]
'B'
>>> lines[2][2]
'D'
  • Related