0

I have datafram like this:

A   B   C   D   E   F
1   2   3   4   5   6
7   8   9   10  11  12
13  14  15  16  17  18

and I create new column by merging columns after C by:

df['new'] = df[df.columns[3:]].apply(lambda x: ','.join(x.dropna().astype(str)), axis=1)

So, now result is:

A   B   C   D   E   F   new
1   2   3   4   5   6   4,5,6
7   8   9   10  11  12  10,11,12
13  14  15  16  17  18  16,17,18

But I want new column as list. like below:

A   B   C   D   E   F   new
1   2   3   4   5   6   [4,5,6]
7   8   9   10  11  12  [10,11,12]
13  14  15  16  17  18  [16,17,18]

what should I do?

2 Answers 2

2

Let us try

df['New'] = df.iloc[:,3:].agg(list,1)
df
    A   B   C   D   E   F           New
0   1   2   3   4   5   6     [4, 5, 6]
1   7   8   9  10  11  12  [10, 11, 12]
2  13  14  15  16  17  18  [16, 17, 18]
Sign up to request clarification or add additional context in comments.

2 Comments

Interesting approach. Can you please explain what agg(list,1) is doing?
agg row value to one list ~ axis = 1 means check row ~
0

Select your desired columns, convert to a 2d list, then shove them all into 1 series.

df["new"] = df.loc[:, "D":"F"].to_numpy().tolist()

print(df)
    A   B   C   D   E   F           new
0   1   2   3   4   5   6     [4, 5, 6]
1   7   8   9  10  11  12  [10, 11, 12]
2  13  14  15  16  17  18  [16, 17, 18]

1 Comment

Honestly, I do not know the exact name and count of the columns because of this I can only use @BEN_YO answer. Anyway, Thanks.

Your Answer

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