Select cell from Pandas Dataframe and convert to int

367 views Asked by At

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]

3

There are 3 answers

0
Joooeey On BEST ANSWER

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:

import pandas as pd

df = pd.DataFrame({"name": ['John', 'George', 'Ray'], "score": [123, 321, 112]})
x = df.set_index("name").loc["John", "score"]

list_ = []
list_.append(x)
print(list_)

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.

1
jjk On

try:

list.append(x[0])

returns:

list
[123]
2
AudioBubble On

this could help

import pandas as pd

df = pd.DataFrame({"name": ['John', 'George', 'Ray'], "score": [123, 321, 112]})

x = df.loc[df['name'] == 'John', 'score'].reset_index(drop=True)
x = x.item()  # Convert the Series to a single integer value using .item()
print(x)  # Output: 123

my_list = []
my_list.append(x)
print(my_list)  # Output: [123]