将Dates(Series)列从一个DataFrame添加到其他Pandas,Python

时间:2016-10-25 11:38:10

标签: python datetime pandas dataframe series

我正在尝试播放'从df1到df2的日期列。

在df1中,我有所有用户的名字及其基本信息。 在df2中,我列出了用户的购买清单。

df1 and df2 code

假设我有一个更大的数据集(上面为示例创建),我如何将df1 [' DoB']列添加到df2?

我已尝试过concat()和merge(),但它们似乎都不起作用:

code and error

它似乎工作的唯一方法是,只有将df1和df2合并在一起,然后才删除我不需要的列。但如果我有数十个不需要的列,那将是非常有问题的。

完整代码(包括抛出错误的行):

import pandas as pd
df1 = pd.DataFrame(columns=['Name','Age','DoB','HomeTown'])

df1['Name'] = ['John', 'Jack', 'Wendy','Paul']
df1['Age'] = [25,23,30,31]
df1['DoB'] = pd.to_datetime(['04-01-2012', '03-02-1991', '04-10-1986', '06-03-1985'], dayfirst=True)
df1['HomeTown'] = ['London', 'Brighton', 'Manchester', 'Jersey']

df2 = pd.DataFrame(columns=['Name','Purchase'])
df2['Name'] = ['John','Wendy','John','Jack','Wendy','Jack','John','John']
df2['Purchase'] = ['fridge','coffee','washingmachine','tickets','iPhone','stove','notebook','laptop']

df2 = df2.concat(df1) # error

df2 = df2.merge(df1['DoB'], on='Name', how='left') #error

df2 = df2.merge(df1, on='Name', how='left')
del df2['Age'], df2['HomeTown']
df2 #that's how i want it to look like 

非常感谢任何帮助。谢谢:))

1 个答案:

答案 0 :(得分:1)

我认为您需要merge子集[['Name','DoB']] - 需要Name列才能进行匹配:

print (df1[['Name','DoB']])
    Name        DoB
0   John 2012-01-04
1   Jack 1991-02-03
2  Wendy 1986-10-04
3   Paul 1985-03-06

df2 = df2.merge(df1[['Name','DoB']], on='Name', how='left')
print (df2)
    Name        Purchase        DoB
0   John          fridge 2012-01-04
1  Wendy          coffee 1986-10-04
2   John  washingmachine 2012-01-04
3   Jack         tickets 1991-02-03
4  Wendy          iPhone 1986-10-04
5   Jack           stove 1991-02-03
6   John        notebook 2012-01-04
7   John          laptop 2012-01-04

系列s map的另一个解决方案:

s = df1.set_index('Name')['DoB']
print (s)
Name
John    2012-01-04
Jack    1991-02-03
Wendy   1986-10-04
Paul    1985-03-06
Name: DoB, dtype: datetime64[ns]

df2['DoB'] = df2.Name.map(s)
print (df2)
    Name        Purchase        DoB
0   John          fridge 2012-01-04
1  Wendy          coffee 1986-10-04
2   John  washingmachine 2012-01-04
3   Jack         tickets 1991-02-03
4  Wendy          iPhone 1986-10-04
5   Jack           stove 1991-02-03
6   John        notebook 2012-01-04
7   John          laptop 2012-01-04