1

I use Python , and connection with sql server. I selected from the data in sql server.

CustomerNumber	TransactionDate
1	                2/3/2019
1	                12/4/2019
1	                12/17/2019
2                	1/4/2019
2	                4/4/2019
3	                7/5/2019
4	                7/7/2019
4	                9/5/2019
4	                9/15/2019
4                	10/15/2019

I want convert to array base on CustomerNumber

[1 2/3/2019 12/4/2019 12/17/2019 ]
[2 1/4/2019 4/4/2019]
[3 7/5/2019]
[4 7/5/2019 7/7/2019 9/5/2019 9/15/2019 10/15/2019]

I am python beginner. So I look forward to your feedback. Thanks you for your help.

1
  • why do you want to do that? (I think there's a better solution...) Commented May 16, 2019 at 3:18

2 Answers 2

2

Since I think that is pandas DataFrame , here is a way from pandas

s=df.groupby('CustomerNumber').TransactionDate.apply(list).reset_index()
s
Out[49]: 
   CustomerNumber                              TransactionDate
0               1            [2/3/2019, 12/4/2019, 12/17/2019]
1               2                         [1/4/2019, 4/4/2019]
2               3                                   [7/5/2019]
3               4  [7/7/2019, 9/5/2019, 9/15/2019, 10/15/2019]
l=(s.CustomerNumber.apply(lambda x : [x])+s.TransactionDate).tolist()
l
Out[50]: 
[[1, '2/3/2019', '12/4/2019', '12/17/2019'],
 [2, '1/4/2019', '4/4/2019'],
 [3, '7/5/2019'],
 [4, '7/7/2019', '9/5/2019', '9/15/2019', '10/15/2019']]
Sign up to request clarification or add additional context in comments.

1 Comment

@TrinhPham hehe happy coding
0

I recommend you read your data into a pandas dataframe using pandas.read_sql(https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_sql.html). Make sure to have the proper arguments and pay attention to the 'con' argument for which you specify the connection to your SQL database.

Once you have it in a pandas data frame with two columns (customer_number & transaction date), it becomes a simple groupby operation:

df.groupby(['CustomerNumber'])['TransactionDate'].apply(list)

This should group by on CustomerNumber and append the respective dates to a list for each unique customer number.

1 Comment

Ok , Thank maverick

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.