Fixing String Formatting Issues in pandas Series with Concatenation and Looping

The issue is that in the perc_fluxes1 function, you’re trying to use string formatting ("perc_{}"), but df[column] returns a pandas Series (which is an array-like object), not a string.

To fix this, you can use string concatenation instead:

def perc_fluxes(x):
    x = df.columns[2:]  # to not consider the column 'A' and 'B'
    for i in x:
        y = (i/(df['A']*df['B']))*100

    for column in df.columns[2:]:
        new_column = "perc_" + column
        df[new_column] = df[column].apply(perc_fluxes)

By using new_column = "perc_" + column, you’re creating a string by concatenating the strings "perc_" and column. This will correctly create the column names as desired.

Note that I also removed the outer loop, which was not necessary. The inner loop should iterate over the columns, not the labels of the Series.


Last modified on 2023-10-28