Search code examples
pythonsearchsave

saving results in csv file


I have two csv file: aaa and bbb. aaa file have 4 column as follow name

 2  0 0 1
 7  0 1 1
 8  1 1 0

and bbb have one column as follow 7 8 I want to search about 7,8 (bbb) in file aaa then get whole row of 7 and 8 in aaa as a result i.e i want to get 0 1 1 and 1 1 0 as a result then save it in csv file.

aaa=pd.read_csv('aaa.csv',index_col ="name")
bbb=pd.read_csv('bbb.csv', header=None)
c=bbb[0].values
for i in c: 
  res=aaa.loc[i]
  print(res)
for i in range(0,2):
  print(res[i])
import csv
def Save(res):
    with open('Saved.csv', 'a') as Saved:
       cw = csv.writer(Saved)
       cw.writerow([res])

Solution

  • df1 = pd.read_csv('aaa.csv')
    df2 = pd.read_csv('bbb.csv', header=None)
    keepRow = df2[0].values
    
    # Get rows that have on of the keepRow values in column 0
    df3 = df1.loc[df1["firstColumn"].isin(keepRow)]
    
    # drop the keepRow column
    df3= df3.drop("firstColumn", axis=1)
    
    #write to csv
    df3.to_csv("ok.csv", index=False)