2

I have column names in list within list with different size like [["a","b","c"],["d","e"],["f"]] also few of the columns contains NaN.

|a b c d e f|

|1 2 3 4 5 6|

|1 2 3 Nan NaN 6|

|1 2 3 4 inf 6|

The result should be the sum of a list within a list like g=a+b+c, h=d+e, i=f which are column names. NaN sum should result NaN, not 0. How to do that in a loop?

Expected Output

|g h i|

|6 9 6|

|6 NaN 6|

|6 inf 6|

3
  • Can you add expected output? Commented Feb 12, 2020 at 6:14
  • Expected Output added Commented Feb 12, 2020 at 6:44
  • Super, answer was edited, please check it. Commented Feb 12, 2020 at 6:48

1 Answer 1

3

Use list comprehension:

L = [["a","b","c"],["d","e"],["f"]]

a = [df[x].sum(axis=1, min_count=1) for x in L]

Loop solution:

a = []
for x in L:
    a.append(df[x].sum(axis=1, min_count=1))

print (a)
[0    6
1    6
2    6
dtype: int64, 0    9.0
1    NaN
2    inf
dtype: float64, 0    6
1    6
2    6
dtype: int64]

And then add concat:

df1 = pd.concat(a, axis=1, keys=['g','h','i'])
print (df1)
   g    h  i
0  6  9.0  6
1  6  NaN  6
2  6  inf  6
Sign up to request clarification or add additional context in comments.

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.