Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

python - join two dataframe on date column and add new column

I have two dataframes.

Frame

enter image description here

df_stock

enter image description here

I want to join both on date column. So that where there is same date in df_stock, the innovationscore column value should be populated. Like in df_stock, where Date is 2020-10-19, 1 should be populated in InnovationScore column. What I need after joining is Date, Open, Close and InnovationScore columns. What I have done is.

df_stock.join(frame, lsuffix='Date', rsuffix='Date')

which results in this which is not intended. I don't want DateDate column and NAN. if not value in InnovationScore, it should be 0.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use DataFrame.merge with left join and DataFrame.fillna:

df = df_stock.merge(frame, on='Date', how='left').fillna({'InnovationScore':0})

Or with Series.fillna:

df = df_stock.merge(frame, on='Date', how='left')
df['InnovationScore'] = df['InnovationScore'].fillna(0).astype(int)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...