2

I have create a DataFrame using pandas by reading a csv file. What I want to do is iterate down the rows (for the values in column 1) into a certain array, and do the same for the values in column 2 for a different array. This seems like it would normally be a fairly easy thing to do, so I think I am missing something, however I can't find much online that doesn't get too complicated and doesn't seem to do what I want. Stack questions like this one appear to be asking the same thing, but the answers are long and complicated. Is there no way to do this in a few lines of code? Here is what I have set up:

import pandas as pd 

#available possible players
playerNames = []

df = pd.read_csv('Fantasy Week 1.csv')

What I anticipate I should be able to do would be something like:

for row in df.columns[1]:
    playerNames.append(row)

This however does not return the desired result.

Essentially, if df =
[1,2,3
4,5,6
7,8,9], I would want my array to be [1,4,7]

1 Answer 1

1

Do:

for row in df[df.columns[1]]:
    playerNames.append(row)

Or even better:

print(df[df.columns[1]].tolist())

In this case you want the 1st column's values so do:

for row in df[df.columns[0]]:
    playerNames.append(row)

Or even better:

print(df[df.columns[0]].tolist())
Sign up to request clarification or add additional context in comments.

4 Comments

thank you for the prompt response. I recognize that this does what I want, but can you give me a bit of a break down of what exactly is happening in df[df.columns[1]]?
@AlekPiasecki df.columns returns the columns of a dataframe, df.columns[1] returns the 2nd column name, then we want to get the data of the column so do: df[df.columns[1]]
@AlekPiasecki Edited my answer
can I grab multiple columns at a time? I want to assign the value from the current row, column 1 for a key of a dictionary and the value from the current row, column 2 for the value of that dictionary?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.