Franco Piccolo
Franco Piccolo

Reputation: 7410

Join pandas row with column

I have this row dataframe:

df = pd.DataFrame({'make':'toyota', 'model':'yaris'}, index=[0])
df

    make    model
0   toyota  yaris

And have this other column dataframe:

df_prices = pd.DataFrame({'prices':[1,2,3,4]})
df_prices

    prices
0   1
1   2
2   3
3   4

And I would like to join them to obtain:

    make    model   prices
0   toyota  yaris   1
1   toyota  yaris   2
2   toyota  yaris   3
3   toyota  yaris   4

Upvotes: 2

Views: 404

Answers (2)

U13-Forward
U13-Forward

Reputation: 71580

Try:

df=df_prices.join(df).ffill()
print(df)

   prices    make  model
0       1  toyota  yaris
1       2  toyota  yaris
2       3  toyota  yaris
3       4  toyota  yaris

If care about columns:

df=df[['make','model','prices']]
print(df)

     make  model  prices
0  toyota  yaris       1
1  toyota  yaris       2
2  toyota  yaris       3
3  toyota  yaris       4

join + ffill!!!

Update (thanks to @larsr's comment):

df=df.join(df_prices, how='outer').ffill()
print(df)

Would do it, and also fix column orders.

Upvotes: 7

Mohamed Thasin ah
Mohamed Thasin ah

Reputation: 11192

What about this,

print pd.merge(df,df_prices,left_index=True,right_index=True,how='outer').fillna(method='ffill')

Python 3:

print(pd.merge(df,df_prices,left_index=True,right_index=True,how='outer').fillna(method='ffill'))

For more specific,

print pd.concat([df,df_prices],axis=1).ffill()

Output:

     make  model  prices
0  toyota  yaris       1
1  toyota  yaris       2
2  toyota  yaris       3
3  toyota  yaris       4

Upvotes: 0

Related Questions