繁体   English   中英

我正在尝试在Python中将一个数据框的列添加到另一个数据框,但不是不成功

[英]I'm trying to add a column from one dataframe to another in Python, but not I'm not succcessful

我有这两个数据帧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)

Pandas正在将数据连接到索引上,但是您的系列与父数据框没有相同的索引。 相反,您可以向其提供数据的numpy数组。

cd2['cat_gm'] = cd3['cat_gm'].values

首先,您必须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.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM