panda
panda

Reputation: 625

How to replace dataframes column value for all the csv files in a folder by other dataframe column value?

I have the following dataframe sheet1

Id  Snack      Price   
5   Orange      55    
7   Apple       53    
8   Muskmelon   33 

I have the other dataframe replace

 Snack        Cat
   Orange      a    
   Apple       b    
   Muskmelon   c

For replacing column value with other column value this is the code

sheet1['snack'] = sheet1['snack'].map(replace.set_index('Snack')['Cat'])

So I will get this after the above code.

 Id  Snack      Price   
    5   a      55    
    7   b      53    
    8   c      33 

How do I do the same operation for all the csv sheets present in the folder.

Input: https://www.dropbox.com/sh/1mbgjtrr6t069w1/AADC3ZrRZf33QBil63m1mxz_a?dl=0

Output: Replace Snack column sheet values with replace dataframe cat values for all the files in a folder.

Upvotes: 1

Views: 96

Answers (1)

jezrael
jezrael

Reputation: 862731

I believe you need glob for list of files, then loop and create DataFrame, map and last save back:

import glob

s = replace.set_index('Snack')['Cat']

for file in glob.glob('files/*.csv'):
    #df = pd.read_csv(file)
    df['Snack'] = df['Snack'].map(s)
    df.to_csv(f'{file}', index=False)

Upvotes: 2

Related Questions