Say I have the following DataFrame
Letter Number A 1 B 2 C 3 D 4
Which can be obtained through the following code
import pandas as pd
letters=pd.Series(('A', 'B', 'C', 'D'))
numbers=pd.Series((1, 2, 3, 4))
keys=('Letters', 'Numbers')
df=pd.concat((letters, numbers), axis=1, keys=keys)
Now I want to get the value C from the column Letters.
The command line
df[df.Letters=='C'].Letters
will return
2 C Name: Letters, dtype: object
How can I get only the value C and not the whole two line output?
Nobody mentioned it, but you can also simply use loc
with the index and column labels.
df.loc[2, 'Letters']
# 'C'
Or, if you prefer to use "Numbers" column as reference, you can also set is as an index.
df.set_index('Numbers').loc[3, 'Letters']
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'
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 .
.
Source: Stackoverflow.com