0

I have dataframe like df=

   S  A4  P
0   1   3  7
1   1   5  4
2   1   7  5
3   1  10  6
4   3  12  2
5   3  15  3
6   3   1  7
7   2   2  4
8   2   3  5
9   2   4  6
10  2   5  2
11  4   6  3

I am trying to extract A4 column to numpy array and handle a 2d numpy array which has spesific row number. Row number is coming from the value count of S column. The array that i am searching is

[[3, 5, 7, 10], [12, 15, 1], [2, 3, 4, 5], [6]]

What can be the most pythonic way?

2 Answers 2

1

Data:

df = pd.DataFrame({'S': {0: 1, 1: 1, 2: 1, 3: 1, 4: 3, 5: 3, 6: 3, 7: 2, 8: 2, 9: 2, 10: 2, 11: 4}, 'A4': {0: 3, 1: 5, 2: 7, 3: 10, 4: 12, 5: 15, 6: 1, 7: 2, 8: 3, 9: 4, 10: 5, 11: 6}, 'P': {0: 7, 1: 4, 2: 5, 3: 6, 4: 2, 5: 3, 6: 7, 7: 4, 8: 5, 9: 6, 10: 2, 11: 3}})

df

    S   A4  P
0   1   3   7
1   1   5   4
2   1   7   5
3   1   10  6
4   3   12  2
5   3   15  3
6   3   1   7
7   2   2   4
8   2   3   5
9   2   4   6
10  2   5   2
11  4   6   3
df.groupby("S").apply(lambda df:df.A4.to_list())
S
1    [3, 5, 7, 10]
2     [2, 3, 4, 5]
3      [12, 15, 1]
4              [6]
Sign up to request clarification or add additional context in comments.

Comments

1

You can do groupby

out = df.groupby('S')['A4'].agg(list).tolist()
Out[426]: [[3, 5, 7, 10], [2, 3, 4, 5], [12, 15, 1], [6]]

2 Comments

It is not giving numpy array. It is giving a list?
@MertAçikel correct , numpy array need each sub array have same size , or it just a array of list , i will recommend keep it as list

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.