how define "for" for specified columns to avoid wasting time

Question:

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

Asked By: hamideh

||

Answers:

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)
Answered By: Ignatius Reilly
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.