Jan
Jan

Reputation: 43169

DataFrame value startswith

I have the following dataframe in pandas:

        Datum   Zeit                                     Event
0  14.11.2016  13:00   Veröffentlichung des 9-Monats-Berichtes
1  14.03.2017  13:00            Telefonkonferenz für Analysten
2  14.03.2017  13:00            Telefonkonferenz für Analysten
3  27.04.2017  14:00              Ordentliche Hauptversammlung
4  03.05.2017  14:00                         Dividendenzahlung
5  15.05.2017  14:00                    Bericht zum 1. Quartal
6  14.08.2017  14:00           Telefonkonferenz für Investoren
7  14.08.2017  14:00            Telefonkonferenz für Analysten
8  14.08.2017  14:00  Veröffentlichung des Halbjahresberichtes

I am looking for the dates of quarterly reports here ("Bericht" in good old German).
I can select the row via

df.loc[df["Event"].str.startswith("Bericht"), "Datum"]

which returns a Series object like

5    15.05.2017
Name: Datum, dtype: object

However, I only want to have the date - am I overcomplicating things here?

Upvotes: 7

Views: 14191

Answers (2)

Qikai
Qikai

Reputation: 34

You are doing well. If you only want to have the date, you can do:

df.loc[df["Event"].str.startswith("Bericht"), "Datum"].values

This returns a list of dates.

Upvotes: 1

EdChum
EdChum

Reputation: 394179

By default a Series is returned when accessing a specific column and row in a DataFrame if you want a scalar value then you can access the array element using .values to return np array and then indexing into it:

In [101]:
df.loc[df["Event"].str.startswith("Bericht"), "Datum"].values[0]

Out[101]:
'15.05.2017'

For safety you should check whether your selection yields any results prior to indexing into it, otherwise you get a KeyError:

if len(df.loc[df["Event"].str.startswith("Bericht"), "Datum"]) > 0:
   return df.loc[df["Event"].str.startswith("Bericht"), "Datum"].values[0]

Upvotes: 10

Related Questions