How to get a value from a Pandas DataFrame and not the index and object type
--
Track title: CC I Beethoven Sonata No 31 in A Flat M
--
Chapters
00:00 Question
00:49 Accepted answer (Score 232)
01:18 Answer 2 (Score 89)
01:59 Answer 3 (Score 3)
02:24 Answer 4 (Score 3)
02:49 Thank you
--
Full question
https://stackoverflow.com/questions/3078...
Accepted answer links:
[Pandas Index doc]: http://pandas.pydata.org/pandas-docs/sta...
[Pandas Series doc]: http://pandas.pydata.org/pandas-docs/sta...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #dataframe
#avk47
ACCEPTED ANSWER
Score 252
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.
ANSWER 2
Score 95
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 ..
ANSWER 3
Score 4
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'
ANSWER 4
Score 4
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().