简体   繁体   English

熊猫-根据字典中的日期填写栏

[英]Pandas - Fill column depending on date in dictionary

I am trying to fill a dataframe column with the value of two other columns depending on a date i have in a dictionary. 我试图根据我在字典中的日期,用其他两个列的值填充dataframe列。 It looks like this: 看起来像这样:

# the input date 
input_date = pd.to_datetime('04.12.2017 12:00:00', format='%d.%m.%Y %H:%M:%S')

# the dict
dict = {'A': pd.to_datetime('06.12.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),
        'B': pd.to_datetime('08.11.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),
        'C': pd.to_datetime('15.10.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),

# the df
d = {'result':[None,None,None], 
     'id_1':[1,2,3], 'id_2':[10,20,30], 
     'dict_key':['A', 'B', 'A']}
df = pd.DataFrame(d)

My criteria is: If the input date is after the date in the dictonary, take id_1, else take id_2 我的标准是:如果输入日期晚于字典中的日期,则输入id_1,否则输入id_2

The result would like this: 结果如下:

    dict_key    id_1    id_2    result
0   A           1       10      10
1   B           2       20      2
2   A           3       30      30
In [20]: df['result'] = np.where(df.dict_key.map(dct) >= input_date, df['id_2'], df['id_1'])

In [21]: df
Out[21]:
  dict_key  id_1  id_2  result
0        A     1    10      10
1        B     2    20       2
2        A     3    30      30

where dct is a dictionary that is called dict in your question. 其中dct是在您的问题中称为dict We should try to avoid overwriting standard keywords (like list , dict , etc.). 我们应该尽量避免覆盖标准关键字(例如listdict等)。

Use: 采用:

d1 = {'A': pd.to_datetime('06.12.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),
        'B': pd.to_datetime('08.11.2017 12:00:00', format='%d.%m.%Y %H:%M:%S'),
        'C': pd.to_datetime('15.10.2017 12:00:00', format='%d.%m.%Y %H:%M:%S')}

d2 = {k:v for k,v in d1.items() if v > input_date}
print (d2)
{'A': Timestamp('2017-12-06 12:00:00')}

df['result'] = np.where(df.dict_key.isin(d2.keys()), df.id_2, df.id_1)
print (df)
  dict_key  id_1  id_2  result
0        A     1    10      10
1        B     2    20       2
2        A     3    30      30

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

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