在索引上将两个pandas数据帧合并在一起时出错

2024-10-02 18:17:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在索引上合并两个熊猫数据帧,但我得到错误。。。在

这是df1

      alleles  chrom  pos strand  assembly#  center  protLSID  assayLSID  
rs#
TP121     C/A      0  121      +        NaN     NaN       NaN        NaN
TP135     G/A      0  135      +        NaN     NaN       NaN        NaN
TP283     A/G      0  283      +        NaN     NaN       NaN        NaN
TP302     C/T      0  302      +        NaN     NaN       NaN        NaN
TP334     T/G      0  334      +        NaN     NaN       NaN        NaN

这是df2

^{pr2}$

当我尝试合并时,我得到了这个错误-"['TP121' 'TP135' 'TP283' ..., 'TP251072' 'TP251178' 'TP251355'] not in index",当它们明显地在两个索引中时。我哪里做错了?在

pd.merge(df1, df2, on=df.index, how = "outer")

Tags: 数据posindex错误assemblynancenterdf1
2条回答

你可以试试:

pd.concat([df1, df2], axis=1)

对于您的任务,pd.concat比合并更好。但是使用merge可以将两个数据帧与列rs#上的reset_index合并:

pd.merge(df1.reset_index(), df2.reset_index(), on='rs#')

如果需要生成的dataframe具有可以使用的原始索引,那么set_index

^{pr2}$

相关问题 更多 >