I have a data frame which has 50 columns. I would like to sum 10 columns and store the same into new column name (called savings to be created). I have 10 files, hence want to use function and apply the same to all the files.
Right now I am using iloc and it's working fine. I don't know how to bring this into a function?
my dataframe name called df.
df['savings'] = df.iloc[:,11:27].sum(axis = 1).round(2)
I want to use function and checked the below. But it is not working
def saving(x):
x = df.iloc[:,11:27].sum(axis = 1).round(2)
return(x)
df['savings] = df.applymap(x)
This is not working. Any suggestion. I have 10 different files and want to do the same sum.
I believe you need pass DataFrame
to function
:
def saving(x):
x['savings'] = x.iloc[:,11:27].sum(axis = 1).round(2)
return x
If need apply function to DataFrame
use DataFrame.pipe
:
df = df.pipe(saving)
Or:
df = saving(df)
Loop by files, create DataFrame
s and apply function if need apply function to multiple DataFrames:
import glob
for f in glob.glob('files/*.csv'):
df = pd.read_csv(f).pipe(saving)
print (df)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments