J.Ben
J.Ben

Reputation: 11

I want to merge a DataFrame with a CSV

I need to merge 1 df with 1 csv. df1 contains only 1 columns (id list of the product I want to update) df2 contains 2 columns (id of all the products, quantity)

df1=pd.read_csv(id_file, header=0, index_col=False)
df2 = pd.DataFrame(data=result_q)
df3=pd.merge(df1, df2)

What I want: a dataframe that contains only id from csv/df1 merge with the quantities of df2 for the same id

Upvotes: 1

Views: 123

Answers (3)

J.Ben
J.Ben

Reputation: 11

I've found the solution. I needed to reset the index for my df2

df1=pd.read_csv(id_file)
df2 = pd.DataFrame(data=result_q).reset_index()

df1['id'] = pd.to_numeric(df1['id'], errors = 'coerce')
df2['id'] = pd.to_numeric(df2['id'], errors = 'coerce')



df3=df1.merge(df2, on='id')

Thank you everyone!

Upvotes: 0

Akshay Sapra
Akshay Sapra

Reputation: 496

you can use new_df= pd.merge(df1,df2, on=['Product_id'])

Upvotes: 0

if you want only the products that ya have in first data_frame you can use this:

df_1
Out[11]: 
   id
0   1
1   2
2   4
3   5

df_2
Out[12]: 
   id prod
0   1    a
1   2    b
2   3    c
3   4    d
4   5    e
5   6    f
6   7    g
7   8    h

df_3 = df_1.merge(df_2,on='id')
df_3
Out[14]: 
   id prod
0   1    a
1   2    b
2   4    d
3   5    e

you neede use the parameter on='column' so the will generate a new df only with the correspondent rows that have the same id.

Upvotes: 1

Related Questions