在pandas中添加两行以形成一个长行

时间:2018-02-16 11:45:04

标签: python pandas dataframe

希望是一个简单的问题,但我有两个DataFrame,根据我正在寻找的名称,我从中抽取了一行:

mmb_df[mmb_df['name'] == mmb_name]

jps_df[jps_df['name'] == jps_name]

这给了我两行,每行大约60列,而我想做的就是将它们组合在一起,这样我就有了一行120列。有些列确实有相同的名称,但我不确定这是否有所不同。

如果我有两行,例如:

name     tag   x    y 
001_Dc   F     243  567

name     tag   position1    position2
jps_043  EW    908          219

我只需要它们:

name     tag   x    y     name      tag   position1   position2
001_Dc   F     243  567   jps_043   EW    908         219

我确信这可以轻松完成,但我没有运气。

2 个答案:

答案 0 :(得分:5)

我认为您首先需要相同的索引,然后使用join

这里使用concat不是一个好的解决方案,因为不要避免重复的列名。

pd.concat([a,b], axis=1)
a = mmb_df[mmb_df['name'] == mmb_name]
b = jps_df[jps_df['name'] == jps_name]

#same both indices
b.index = a.index

#or implicitely set indices
#a.index = [0] 
#b.index = [0] 
c = a.join(b, lsuffix='first')

如果可能某些条件返回更多行,则可以先选择:

a = a.iloc[[0]]
b = b.iloc[[0]]
b.index = a.index
c = a.join(b, lsuffix='first')

或者使用0 []a = a.iloc[[0]].set_index([[0]]) b = b.iloc[[0]].set_index([[0]]) c = a.join(b, lsuffix='first') 的第一个索引设置为True

loc

仅针对第一行的解决方案 - 按set_index获取第a = mmb_df.loc[[(mmb_df['name'] == mmb_name).idxmax()]].set_index([[0]]) b = jps_df.loc[[(jps_df['name'] == jps_name).idxmax()]].set_index([[0]]) c = a.join(b, lsuffix='first') 行,然后按person : { name : "Test", surname : "Test", age : 40, salary : 5000 currency : "dollar", currency_sign : "$", . . . } 选择:

axios.post('update/currency', {
    currency : 'euro',
    token : '...'
}).then( res => {
    if ( res.response.data.message == 'success' ) {

        res.response.data.params.forEach( (val, index) => {
            // what should i do in here without touching the others
            // forexample params has this props
            // currency
            // currency_sign
            //salary
        });

        // setState to person
        this.setState( ? );
    }
}, err => ... );

答案 1 :(得分:3)

Pandas merge也可以起作用:

this

输出:

df1.index = df2.index
pd.merge(df1, df2, how='inner',  left_index=True, right_index=True, sort=True, suffixes=('_x', '_y'))
相关问题