从另一个列更改列中的df [英] Change column in df from column from another

查看:99
本文介绍了从另一个列更改列中的df的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数据:

                 date                      id 
0     2016-06-17 06:25:05    yans.bouts@yandex.ru    
1     2016-06-17 06:25:07    yans.bouts@yandex.ru       
2     2016-06-17 06:25:10    titovtanya@yandex.ru         
3     2016-06-17 06:25:11    titovtanya@yandex.ru

其他数据



Other data

Email,UTC shift
yans.bouts@yandex.ru,5
inkin_sam@mail.ru,3
titovtanya@yandex.ru,3
dasha.dasha.kovaleva@mail.ru,2

我需要将 UTC shift 添加到第一个文件 date hours
欲望输出:

I need to add UTC shift to first file date to hours. Desire output:

                     date                      id 
0     2016-06-17 11:25:05    yans.bouts@yandex.ru    
1     2016-06-17 11:25:07    yans.bouts@yandex.ru       
2     2016-06-17 09:25:10    titovtanya@yandex.ru         
3     2016-06-17 09:25:11    titovtanya@yandex.ru

我转换 date 到datetime,但我不知道如何将 UTC转换转换为小时。

I convert date to datetime, but I don't know, how convert UTC shift to hours.

推荐答案

您需要先转换 to_datetime 日期如果 dtype 不是 datetime id 和电子邮件合并 rel =nofollow> code>。然后转换 to_timedelta UTC移位,添加到日期,最后 drop 不必要的列: p>

You need first convert to_datetime column date if dtype is not datetime, merge by columns id and Email. Then convert to_timedelta column UTC shift, add to date and last drop unnecessary columns:

import pandas as pd


df1 = pd.DataFrame({'date': {0: '2016-06-17 06:25:05', 1: '2016-06-17 06:25:07', 2: '2016-06-17 06:25:10', 3: '2016-06-17 06:25:11'}, 
                      'id': {0: 'yans.bouts@yandex.ru', 1: 'yans.bouts@yandex.ru', 2: 'titovtanya@yandex.ru', 3: 'titovtanya@yandex.ru'}})

df2 = pd.DataFrame({'Email': {0: 'yans.bouts@yandex.ru', 1: 'inkin_sam@mail.ru', 2: 'titovtanya@yandex.ru', 3: 'dasha.dasha.kovaleva@mail.ru'}, 
                    'UTC shift': {0: 5, 1: 3, 2: 3, 3: 2}})

print (df1)
                  date                    id
0  2016-06-17 06:25:05  yans.bouts@yandex.ru
1  2016-06-17 06:25:07  yans.bouts@yandex.ru
2  2016-06-17 06:25:10  titovtanya@yandex.ru
3  2016-06-17 06:25:11  titovtanya@yandex.ru

print (df2)
                          Email  UTC shift
0          yans.bouts@yandex.ru          5
1             inkin_sam@mail.ru          3
2          titovtanya@yandex.ru          3
3  dasha.dasha.kovaleva@mail.ru          2





df1['date'] = pd.to_datetime(df1.date)

df = pd.merge(df1, df2, left_on='id', right_on='Email')
df['date'] += pd.to_timedelta(df['UTC shift'], unit='H')
df.drop(['Email','UTC shift'], axis=1, inplace=True)
print (df)
                 date                    id
0 2016-06-17 11:25:05  yans.bouts@yandex.ru
1 2016-06-17 11:25:07  yans.bouts@yandex.ru
2 2016-06-17 09:25:10  titovtanya@yandex.ru
3 2016-06-17 09:25:11  titovtanya@yandex.ru

这篇关于从另一个列更改列中的df的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆