我有两个数据帧,cd2和cd3。我想将cd3中的cat_gm列添加到cd2中:
cd2
cat rand freq _merge
7 21 0.810730 2 left_only
8 21 0.591324 3 left_only
12 22 0.083941 3 left_only
13 22 0.378123 4 left_only
cd3
cat freq cat_gm _merge
14 11 2 11.0 right_only
15 12 3 12.0 right_only
16 12 4 12.0 right_only
17 12 5 12.0 right_only为了达到我的目标,我尝试了以下代码:
cd2['cat_gm']=pd.Series(cd3['cat_gm'])
cd2
cat rand freq _merge cat_gm
7 21 0.810730 2 left_only NaN
8 21 0.591324 3 left_only NaN
12 22 0.083941 3 left_only NaN
13 22 0.378123 4 left_only NaN如你所见,我得到的都是缺失值。我想要的是:cd2['cat_gm']=pd.Series(cd3['cat_gm'])
cd2
Out[13]:
cat rand freq _merge cat_gm
7 21 0.810730 2 left_only 11.0
8 21 0.591324 3 left_only 12.0
12 22 0.083941 3 left_only 12.0
13 22 0.378123 4 left_only 12.0我哪里错了?
下面的代码是我最初是如何创建cd2和cd3的:
import pandas as pd
import numpy as np
a=pd.DataFrame({'cat':[11,12,21,22],'freq':[2,3,4,5]})
b=pd.DataFrame({'cat':[11,12,21,22],'freq':[3,6,2,3]})
c=pd.Series.to_frame(np.repeat(a['cat'],a['freq']))
d=pd.Series.to_frame(np.repeat(b['cat'],b['freq']))
c['rand']=np.random.uniform(0,1,len(c.index))
c['freq']=c.groupby('cat').cumcount()
d['freq']=d.groupby('cat').cumcount()
c.sort_values(by=['rand'])
d['cat_gm']=d['cat']
cd=pd.merge(c,d,on=['cat','freq'],how='outer',indicator=True)
cd1=cd[cd._merge=='both']
cd2=cd[pd.isna(cd['cat_gm'])==True]
cd2=cd2.drop(['cat_gm'],axis=1)
cd3=cd[pd.isna(cd['rand'])==True]
cd3=cd3.drop(['rand'],axis=1)发布于 2017-12-22 10:01:50
Pandas正在索引上联接数据,但您的系列没有与父数据框相同的索引。相反,您可以向它提供一个数据的numpy数组。
cd2['cat_gm'] = cd3['cat_gm'].values发布于 2017-12-22 11:36:54
首先你必须使用reset_index,
cd2 = cd2.reset_index(drop=True)
cd3 = cd3.reset_index(drop=True)然后使用pd.concat将列从一个数据帧复制到另一个数据帧,
new_df = pd.concat([cd2, cd3[['cat_gm']]], axis=1)现在你得到了你想要的,print(new_df),结果
cat rand freq _merge cat_gm
0 21 0.102928 2 left_only 11.0
1 21 0.803516 3 left_only 12.0
2 22 0.054483 3 left_only 12.0
3 22 0.724568 4 left_only 12.0https://stackoverflow.com/questions/47934825
复制相似问题