Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a value from a Pandas DataFrame and not the index and object type

People also ask

How do I select a value from a DataFrame in Pandas?

Select Data Using Location Index (. This means that you can use dataframe. iloc[0:1, 0:1] to select the cell value at the intersection of the first row and first column of the dataframe. You can expand the range for either the row index or column index to select more data.

How do I print a column from a DataFrame without an index?

To print the DataFrame without indices uses DataFrame. to_string() with index=False parameter. A pandas DataFrame has row indices/index and column names, when printing the DataFrame the row index is printed as the first column.


df[df.Letters=='C'].Letters.item()

This returns the first element in the Index/Series returned from that selection. In this case, the value is always the first element.

EDIT:

Or you can run a loc() and access the first element that way. This was shorter and is the way I have implemented it in the past.

  • Pandas Index doc
  • Pandas Series doc

Use the values attribute to return the values as a np array and then use [0] to get the first value:

In [4]:
df.loc[df.Letters=='C','Letters'].values[0]

Out[4]:
'C'

EDIT

I personally prefer to access the columns using subscript operators:

df.loc[df['Letters'] == 'C', 'Letters'].values[0]

This avoids issues where the column names can have spaces or dashes - which mean that accessing using ..


import pandas as pd

dataset = pd.read_csv("data.csv")
values = list(x for x in dataset["column name"])

>>> values[0]
'item_0'

edit:

actually, you can just index the dataset like any old array.

import pandas as pd

dataset = pd.read_csv("data.csv")
first_value = dataset["column name"][0]

>>> print(first_value)
'item_0'

You can use loc with the index and column labels.

df.loc[2, 'Letters']
# 'C'

If you prefer the "Numbers" column as reference, you can set it as index.

df.set_index('Numbers').loc[3, 'Letters']

I find this cleaner as it does not need the [0] or .item().