pandas DataFrame 值开始于

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39589126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:02:49  来源:igfitidea点击:

DataFrame value startswith

pythonpandasdataframe

提问by Jan

I have the following dataframe in pandas:

我在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

我正在这里寻找季度报告的日期(“Bericht”用古德语)。
我可以通过选择行

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

which returns a Seriesobject like

它返回一个Series对象,如

5    15.05.2017
Name: Datum, dtype: object

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

但是,我只想知道日期——我是不是把事情复杂化了?

回答by EdChum

By default a Seriesis returned when accessing a specific column and row in a DataFrameif you want a scalar value then you can access the array element using .valuesto return nparray and then indexing into it:

默认情况下,Series在访问 a 中的特定列和行时返回 aDataFrame如果您想要一个标量值,那么您可以使用.values来访问数组元素返回np数组,然后对其进行索引:

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:

为了安全起见,您应该在索引之前检查您的选择是否产生任何结果,否则您会得到KeyError

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

回答by Qikai

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.

这将返回日期列表。