Home > Enterprise >  how define "for" for specified columns to avoid wasting time
how define "for" for specified columns to avoid wasting time

Time:07-24

My dataset has 54 columns.i want to define a loop ("For") to get some specified columns (20 columns) then apply a simple function . how can i do this? i want to avoid wasting time

CodePudding user response:

So, let's say we have a list with the specified 20 columns, something like ['foo', 'bar', 'baz', ...]

Then we can do

specified_columns = ['foo', 'bar', 'baz']

for column in specified_columns:
    df.['new' column] = df[column].apply(simple_function)

this should create a set of 20 new columns called new_foo, new_bar, etc.

If we had another list with the names of the 20 new columns, in the same order, we could do:

specified_columns = ['foo', 'bar', 'baz']
new_columns = ['bla', 'ble', 'bli']

for i in range(len(specified_columns)):
    df.[new_columns[i]] = df[specified_columns[i]].apply(simple_function)
  • Related