When selecting cell from Dataframe, it returns me Series value and append it to list as series. How to convert cell into single int value?
df = pd.DataFrame({"name": ['John', 'George', 'Ray'], "score": [123, 321, 112]})
x = df.loc[df['name']=='John', 'score'].reset_index(drop=True)
x.astype(int)
x
list=[]
list.append(x)
list
Return me [0 123 Name: score, dtype: int64], but need just [123]
This happens because in general
df["name"] == "John"
could be true for several rows.A simple way to to work around this is to temporarily turn the "name" column into the DataFrame's index with
set_index
:Additional notes:
If you have "John" more than once in the "name" column, you get the same problem with this solution as in your original code.
Depending on your data model, it might make sense to use the names as index permanently by moving
set_index
to the line where you define the DataFrame.It's bad practice to shadow built-in names like
list
because you might need them later.