Alejandro Lee
Alejandro Lee

Reputation: 167

How To Rearrange Data Set?

I am trying to rearrange my data set which currently looks like this:

enter image description here

To this:

enter image description here

I have been manually transposing and adding up the values for each source and trying my hand at using Python to automate this task. Would anybody be so kind to help me get started in the right direction?

Upvotes: 0

Views: 1437

Answers (1)

noslenkwah
noslenkwah

Reputation: 1744

Here's a potential pandas solution.

I made a test csv file. Didn't copy yours verbatim but the structure is there

test_data.csv

Source,10/30/2017,10/31/2017,11/1/2017,11/2/2017,11/3/2017,11/4/2017,11/5/2017
A,10,11,12,13,14,15,16
B,15,16,17,18,19,20,21
C,20,21,22,23,24,25,26
A,25,26,27,28,29,30,31
B,30,31,32,33,34,35,36
C,35,36,37,38,39,40,41

Here's the python code to process the data as you want it

import pandas as pd
df = pd.read_csv('test_data.csv')
df = df.set_index('Source')
ser = df.unstack('Source')
ser = ser.groupby(level=[0, 1]).sum()
ser = ser.sort_index(level=1)

At this point, ser looks like this

            Source
10/30/2017  A         35
10/31/2017  A         37
11/1/2017   A         39
11/2/2017   A         41
11/3/2017   A         43
11/4/2017   A         45
11/5/2017   A         47
10/30/2017  B         45
10/31/2017  B         47
11/1/2017   B         49
11/2/2017   B         51
11/3/2017   B         53
11/4/2017   B         55
11/5/2017   B         57
10/30/2017  C         55
10/31/2017  C         57
11/1/2017   C         59
11/2/2017   C         61
11/3/2017   C         63
11/4/2017   C         65
11/5/2017   C         67
dtype: int64

Anything else beyond this would be formatting and saving it to your liking.

Hope this Helps.

Upvotes: 1

Related Questions