getting string from pandas Series and DataFrames in python?
UPDATE: Not recommended as it truncates long text unless using pandas > 1.0 (not tested)
Not sure what versions of Pandas this works in, but its one other option:
d[d["name"] == "World"].to_string(index=False)
and if more than one row there are other options:
max_rows int, optional
Maximum number of rows to show before truncating. If None, show all.
min_rows int, optional
The number of rows to display in a truncated repr (when number of rows is above max_rows).
There's one method that no one mentioned that might be worth noting. This was a problem I was having where I was doing multiple criteria checks and getting back a single item Series (basically a unique row result). If you have a single item in a Series and just need that item OR know the index of the particular item you want to gather, just do this:
d[d["name"] == "World"].tolist()[0]
for the first (and only) item in a single item Series.
Or this:
d[d["name"] == "World"].tolist()[index]
where index
is the index of the item you are looking for in the Series.
If you want it as a string, you may have to cast as a string if it is not already stringified by default.
As @DSM points out, in general there could be many rows with name 'World'
, so somewhere down the line we'll need to pick one.
One way to do this which seems kind of nice could be 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 row with name 'World' this will return NaN.