0

I have a df that has the following structure:

ID | M | C1 | C2 | C3  
tt | 23| 23 | 563| 234    
rt | 13| 3  | 32 | 67  
cf | 78| 67 | 90 | 90  
di | 45| 12 | 112| 34  

I want to iterate over columns and create additional columns as a result of the next operations:

additional_column1 = M+1+C1
additional_column2 = additional_column1+1+C2
additional_column3 = additional_column2+1+C3  

So that the resulted DF will look like this:

ID | M | C1 | C2 | C3 | AC1 | AC2 | AD3 
tt | 23| 23 | 563| 234|  47 | 611 | 846

I created a for loop, but instead of numbers it fills columns with at 0x7f6e81e2c5e0>

The loop looks as follows:

for c in np.arange(start=1, stop=len(df.columns[1:])+1, step=1):
    df['AC'+str(c)] = lambda c: df.columns[c-1].add(0).sub(df.iloc[:, c])  

Need clue, where I did a mistake. Thanks in advance.

1
  • why are you using lambda at all? Commented Apr 9, 2020 at 17:24

3 Answers 3

1

IIUC:

for c in np.arange(start=1, stop=len(df.columns[1:])+1, step=1):
    df['AC'+str(c)] = df.iloc[: , c-1].add(0).sub(df.iloc[:, c])  
Sign up to request clarification or add additional context in comments.

1 Comment

i am not able to generate the expected output for the first column using this, what am I missing?
0

You can also try df.cumsum() on axis=1 and add the 1 as a range.

# df = df.set_index('ID') if ID is not an index
out = df.assign(**df.cumsum(axis=1).add(range(df.shape[1])).iloc[:,1:].add_prefix('A'))

     M  C1   C2   C3  AC1  AC2  AC3
ID                                 
tt  23  23  563  234   47  611  846
rt  13   3   32   67   17   50  118
cf  78  67   90   90  146  237  328
di  45  12  112   34   58  171  206

Comments

0

You can simply do this: (worked for me)

df = pd.DataFrame(data=[[23,23,563,234],[13,3,32,67],[78,67,90,90],[45,12,112,34]], columns=['M','C1','C2','C3'])

columns = df.columns

last_col = None
for i, col in enumerate(columns):
    if last_col is None:
        last_col = col
        continue
    df['AC' + str(i)] = df[last_col] + 1 + df[col]
    last_col = 'AC' + str(i)


Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.