繁体   English   中英

dataframe如何根据多个条件输入数据

[英]How to input data in dataframe basing on multiple conditions

ID 创建日期 上次修改日期
1 2021 年 3 月 31 日 8:56 2021 年 3 月 31 日 09:46
1 2021 年 3 月 31 日 5:56 2021 年 3 月 31 日 09:48
2 2021 年 3 月 31 日 0:23 2021 年 3 月 31 日 09:47
2 2021 年 3 月 31 日 6:56 2021 年 3 月 31 日 09:46
3 2021 年 3 月 31 日 7:32 2021 年 3 月 31 日 09:46
3 2021 年 3 月 31 日 8:45 2021 年 3 月 31 日 09:46

你好,

对于上表,我需要将每个ID的最早创建日期注释为"Minimal"

import pandas as pd

inputFolder = os.getcwd()
filename = filedialog.askopenfilename(title="Select file:", filetypes=(("xlsx files", ".xlsx"), ("all files", "*.*")), initialdir = inputFolder)
df = pd.read_excel(filename, index_col=None, header=0) 

df.loc[(df.groupby(['BB Global ID']).agg({'Create Date': min})), 'Comment'] = 'Minimal'

print(df)

我试图用 pandas df.loc function 来做,但我遇到了以下错误。

KeyError: "None of [Index([('C', 'r', 'e', 'a', 't', 'e', ' ', 'D', 'a', 't', 'e')], dtype='object')] are in the [index]"

以下是我想要达到的最终结果:

ID 创建日期 上次修改日期 评论
1 2021 年 3 月 31 日 8:56 2021 年 3 月 31 日 09:46
1 2021 年 3 月 31 日 5:56 2021 年 3 月 31 日 09:48 最小
2 2021 年 3 月 31 日 0:23 2021 年 3 月 31 日 09:47 最小
2 2021 年 3 月 31 日 6:56 2021 年 3 月 31 日 09:46
3 2021 年 3 月 31 日 7:32 2021 年 3 月 31 日 09:46 最小
3 2021 年 3 月 31 日 8:45 2021 年 3 月 31 日 09:46

使用GroupBy.transform重复聚合值,因此可以按原始列进行比较:

mask = df.groupby(['BB Global ID'])['Create Date'].transform(min).eq(df['Create Date'])
df.loc[mask, 'Comment'] = 'Minimal'

或者:

df['Comment'] = np.where(mask, 'Minimal', '')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM