1

I have a Pandas Data Frame which contain Three Column. I want to create a multiple list of tuple based on the value in Project Column

print (df)
   Project  Resource  Time
0       P1         0     4
1       P1         2     4
2       P1         1    10
3       P1         3     3
4       P2         1     3
5       P2         3    10
6       P2         0    11
7       P2         2     3
8       P2         0    12
9       P2         3    11
10      P2         1     3
11      P2         2     3
12      P3         0    12

List Tuple i want to create look like this [[(0,4),(2,4),(1,10),(3,3)],[(1,3),(3,10),(0,11),(2,3),(0,12),(3,11),(1,3),(2,3)],[(0,12)]]

I used the following code

tuples = [tuple(x) for x in data.values]

4 Answers 4

2

Use DataFrame.groupby with lambda function and zip, last convert output Series to list:

t  = df.groupby('Project').apply(lambda x: list(zip(x['Resource'], x['Time']))).tolist()
print (t)
[[(0, 4), (2, 4), (1, 10), (3, 3)], 
 [(1, 3), (3, 10), (0, 11), (2, 3), (0, 12), (3, 11), (1, 3), (2, 3)],
 [(0, 12)]]

Another solution:

t  = (df.groupby('Project')['Resource','Time']
        .apply(lambda x: [tuple(y) for y in x.values])
        .tolist())
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the zip function to iterate over several columns of a pandas dataframe:

df = pd.DataFrame({"ressource":[0,2, 1,3], "time":[4,4, 10, 3]})

tuples = [(x,y) for x,y in zip(df['ressource'], df['time'])]

Output:

[(0, 4), (2, 4), (1, 10), (3, 3)]

Comments

1

Try this:

>>> df['zip'] = tuple(zip(df.Resource, df.Time))
>>> df.groupby('Project').agg(lambda x:list(x))['zip'].tolist()
[[(0, 4), (2, 4), (1, 10), (3, 3)],
 [(1, 3), (3, 10), (0, 11), (2, 3), (0, 12), (3, 11), (1, 3), (2, 3)],
 [(0, 12)]]

Comments

0

How about something like this:

listExample=[]
for code in tmpa.loc[:, 'Project'].unique():
   listExample.append([(a, b) for a, b in tmpa[tmpa.loc[:, 'Project']==code].loc[:, ['Resource', 'Time']].values])

It's not pretty, but it should work I think.

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.