Skip to content
Advertisement

Converting a CSV column into a 1D list and then into a 2D list

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.

Advertisement

Answer

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'
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement