我的数据框如下:
slot_id class day base_date
0 1 A Monday 2019-01-21
1 2 B Tuesday 2019-01-22
2 3 C Wednesday 2019-01-23
3 4 C Wednesday 2019-01-23
4 5 C Thursday 2019-01-24
具有以下信息:
example.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 8 entries, 0 to 7
Data columns (total 4 columns):
slot_id 8 non-null int64
class 8 non-null object
day 8 non-null object
base_date 8 non-null object
dtypes: int64(1), object(3)
memory usage: 200.0+ bytes
我想用最小class == "C"
的{{1}}行。我尝试了base_date
的许多组合,但都没有成功,就像这样:
min
上面的代码有什么问题?如何获得满足以上条件的完整行?
完整的example[(example['class']=="C") & min(example['base_date'])]
数据帧:
example
答案 0 :(得分:2)
您可以使用idxmin
:
pd.to_datetime(df.loc[df['class'] == 'C', 'base_date']).idxmin()
# 2
df.iloc[pd.to_datetime(df.loc[df['class'] == 'C', 'base_date']).idxmin()]
slot_id 3
class C
day Wednesday
base_date 2019-01-23
Name: 2, dtype: object
如果您需要重复执行此操作,更好的解决方案是将“ base_date”预先转换为datetime
类型:
df['base_date'] = pd.to_datetime(df['base_date'], errors='coerce')
df.iloc[df.loc[df['class'] == 'C', 'base_date'].idxmin()]
slot_id 3
class C
day Wednesday
base_date 2019-01-23 00:00:00
Name: 2, dtype: object