user2778724
user2778724

Reputation: 49

Python: How to replace once csv file column with another csv file column?

I have two csv files as follows:

one.csv

date time temperature, humidity
01-01-2017,20:45:00,100, 2.1
01-01-2017,21:00:00,100, 2.2
01-01-2017,21:15:00,100,2.3
01-01-2017,21:30:00,100, 2.4
01-01-2017,21:45:00,100, 2.5
01-01-2017,22:00:00,100, 2.6

two.csv

date time temperature
01-01-2017,20:45:00,50
01-01-2017,21:00:00,70
01-01-2017,21:15:00,40
01-01-2017,21:30:00,30
01-01-2017,21:45:00,100
01-01-2017,22:00:00,20

I want to replace values of temperature of one.csv with two.csv based on date and time so the expected output file will be like this:

output.csv
date time temperature, humidity
01-01-2017,20:45:00,50, 2.1
01-01-2017,21:00:00,70, 2.2
01-01-2017,21:15:00,40,2.3
01-01-2017,21:30:00,30, 2.4
01-01-2017,21:45:00,100, 2.5
01-01-2017,22:00:00,20, 2.6

Any help would be highly appreciated. Sorry I am very beginner for python. Thanks

Upvotes: 0

Views: 728

Answers (1)

Sebastien D
Sebastien D

Reputation: 4482

Pandas might help you with that:

import pandas as pd
df1 = pd.read_csv('one.csv')
df2 = pd.read_csv('two.csv')
df_out = df1[['date','time','humidity']].merge(df2[['date','time','temperature']],on=['date','time'])
df_out.to_csv('out.csv',index=False)

Output

    date    time    temperature humidity
01-01-2017  20:45:00    50  2.1
01-01-2017  21:00:00    70  2.2
01-01-2017  21:15:00    40  2.3
01-01-2017  21:30:00    30  2.4
01-01-2017  21:45:00    100 2.5
01-01-2017  22:00:00    20  2.6

Upvotes: 1

Related Questions