Надеюсь, что это охватывает все ситуации, но не может быть точно уверен только с приведенным примером. Я предполагаю, что «ссылка CSV» всегда начинается / заканчивается в первый / последний день месяца (в противном случае вы должны сообщить нам, как справиться с этими ситуациями).
grade.csv
* * 1004
product,start_date,end_date,weight,grade
apple,01/06/2018,31/08/2018,heavy,a
orange,01/06/2018,31/08/2021,heavy,c
banana,01/06/2018,31/08/2021,heavy,b
apple,01/09/2018,01/01/2021,small,a
orange,01/06/2018,31/08/2021,heavy,a
Решение:
import pandas as pd
from dateutil import parser
import datetime as dt
d = {'from': ['apple', 'banana', 'orange', 'banana', 'apple', 'orange'],
'to': ['banana', 'orange', 'apple', 'orange', 'banana', 'apple'],
'month': ['Aug-18', 'Aug-18', 'Aug-18', 'Sept-18', 'Sept-18','Sept-18']}
df = pd.DataFrame(data=d, columns=list(d.keys()) + ['from_weight', 'to_weight', 'from_grade', 'to_grade'])
grade = pd.read_csv('grade.csv')
for entry in df.index:
date = parser.parse(df.loc[entry, 'month'])
for line in grade.index:
date_start = dt.datetime.strptime(grade.loc[line, 'start_date'], '%d/%m/%Y')
date_end = dt.datetime.strptime(grade.loc[line, 'end_date'], '%d/%m/%Y')
if (df.loc[entry, 'from'] == grade.loc[line, 'product']) & (date > date_start) & (date < date_end):
df.loc[entry, 'from_weight'] = grade.loc[line, 'weight']
df.loc[entry, 'from_grade'] = grade.loc[line, 'grade']
if (df.loc[entry, 'to'] == grade.loc[line, 'product']) & (date > date_start) & (date < date_end):
df.loc[entry, 'to_weight'] = grade.loc[line, 'weight']
df.loc[entry, 'to_grade'] = grade.loc[line, 'grade']
print(df)
Выход:
from to month from_weight to_weight from_grade to_grade
0 apple banana Aug-18 heavy heavy a b
1 banana orange Aug-18 heavy heavy b a
2 orange apple Aug-18 heavy heavy a a
3 banana orange Sept-18 heavy heavy b a
4 apple banana Sept-18 small heavy a b
5 orange apple Sept-18 heavy small a a