簡體   English   中英

熊貓-根據字典中的日期填寫欄

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

我試圖根據我在字典中的日期,用其他兩個列的值填充dataframe列。 看起來像這樣:

# 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)

我的標准是:如果輸入日期晚於字典中的日期,則輸入id_1,否則輸入id_2

結果如下:

    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

其中dct是在您的問題中稱為dict 我們應該盡量避免覆蓋標准關鍵字(例如listdict等)。

采用:

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