-1

I have the following code, but when I execute it, it prints the age_groups_list 17 times,

Any idea why?

import pandas as pd
file = pd.read_csv(r"file location")
age_groups_list = []
for var in file[1:]:
    age = file.iloc[:, 10]
    age_groups_list.append(age)
print(age_groups_list)

the idea is that I have a csv file with 16,000 (+) rows and 20 columns, I am picking the age group from index 10, adding it to a list and then print the list, however when printing the list, it does it for 17 time, this image shows the end of the printing output. enter image description here Any idea what am I doing wrong here? thanks

Barmar
  • 741,623
  • 53
  • 500
  • 612
Ali
  • 37
  • 1
  • 5
  • Please post a [mre]. What does `file` contain? Examine it, then replace the `csv` read with a simple assignment of that value. Then the problem can be reproduced. – Tom Karzes Jan 25 '23 at 18:39
  • 1
    I don't see any way this can print more than once, since the `print()` line isn't in the loop. – Barmar Jan 25 '23 at 18:43
  • 2
    If you want to get a list of a dataframe column, use `.tolist()`. See https://stackoverflow.com/questions/22341271/get-list-from-pandas-dataframe-column-or-row – Barmar Jan 25 '23 at 18:46
  • You extract the same column, `age = file.iloc[:, 10]`, **every** iteration of the for loop. – wwii Jan 25 '23 at 19:51
  • [https://pandas.pydata.org/docs/user_guide/indexing.html](https://pandas.pydata.org/docs/user_guide/indexing.html) – wwii Jan 25 '23 at 20:06

1 Answers1

0

file.iloc[:,10] already gives you all the data you need the loop is useless what you see is actually a list of lists. change it to this:

import pandas as pd
file = pd.read_csv(r"file location")
age_groups_list = file.iloc[:, 10]
print(age_groups_list)
Hello
  • 21
  • 1
  • 3
  • It works in this way, thanks, however, any idea why it is behaving like this? and also I want to have it in a list, thanks again – Ali Jan 25 '23 at 18:57
  • 1
    to have it as a list you can use age_groups_list = file.iloc[:, 10].to_list() – Hello Jan 25 '23 at 19:16