Getting string from pandas Series and DataFrames in python?

I have this data file in pandas:

d=pandas.DataFrame([{"a": 1, "b": 1}, {"c": 2, "b": 4}]) d["name"] = ["Hello", "World"] 

I want to select an element based on its string value in the "name" column, and then get the value as a string. To select an item:

 d[d["name"] == "World"]["name"] Out: 1 World Name: name 

The problem is that it does not give a simple string, but is a series. Casting to a string will not help - how can I just get the string "World" from this? Is this the only way?

 d[d["name"] == "World"]["name"].values[0] 

thanks.

+6
source share
2 answers

As @DSM points out, in general there can be many lines with the name 'World' , so somewhere along the line we need to select one.

One way to do this, which seems nice, is to use where (and then max ):

 In [11]: d.name.where(d.name == 'World', np.nan) Out[11]: 0 NaN 1 World Name: name, dtype: object In [12]: d.name.where(d.name == 'World', np.nan).max() Out[12]: 'World' 

Note: if there is no line with the name "World", this will return NaN.

+7
source

There is one method that no one mentioned, which could be noted. This was a problem that I ran into when I performed several criteria checks and returned one element of the series (basically a unique string result). If you have one item in the series and you need this item or know the index of the specific item you want to collect, simply do the following:

 d[d["name"] == "World"].tolist()[0] 

for the first (and only) element in one series of articles.

Or that:

 d[d["name"] == "World"].tolist()[index] 

where index is the index of the element you are looking for in the series.

If you want it to be like a string, you may need to execute the string as a string if it is still not gated.

+7
source

All Articles