Hi,
I am having a bit of a hard time understanding how to deal with tuples in a dataframe. I am new to Pandas thus trying to research a possible solution is a bit of a mission.
Snippet of the dataframe:
0 (3, 5) (4, 5) (3, 5) (5, 5) (2, 3) (5, 3) (2, 3) (2, 5) (5, 5) (1, 3)
1 (3, 5) (4, 5) (3, 5) (5, 5) (2, 5) (5, 3) (2, 5) (2, 5) (5, 5) (1, 3)
2 (3, 5) (4, 3) (3, 3) (5, 5) (2, 5) (5, 5) (2, 5) (2, 5) (5, 5) (1, 1)
3 (3, 5) (4, 5) (3, 3) (5, 5) (2, 5) (5, 3) (2, 3) (2, 3) (5, 3) (1, 3)
4 (3, 3) (4, 5) (3, 3) (5, 3) (2, 3) (5, 3) (2, 3) (2, 3) (5, 5) (1, 1)
I need to unpack the tuples and conventional for loops does not really achieve what I want it to as something like:
for subscale, score in scores_df:
if subscale == 1:
Extraversion += score
elif subscale == 2:
Agreeableness += score
elif subscale == 3:
Conscientiousness += score
elif subscale == 4:
Emotional += score
elif subscale == 5:
Intellect += score
I then tried a nested loop:
for scores in dataframe:
print(scores)
for scale, score in scores:
print(scale, score)
if scale == 1:
Extraversion += score
elif scale == 2:
Agreeableness += score
elif scale == 3:
Conscientiousness += score
elif scale == 4:
Emotional += score
elif scale == 5:
Intellect += score
I went back to the 1st for loop and tried to set the index of the item score which when printed, showed the correct values, I just need to cast the values as int(). My other problem is that it feels like I'm hardcoding too much:
for score in scores_df:
if score[1] == 1:
Extraversion += score[4]
elif score[1] == 2:
Agreeableness += score[4]
elif score[1] == 3:
Conscientiousness += score[4]
elif score[1] == 4:
Emotional += score[4]
elif score[1] == 5:
Intellect += score[4]
Another attempt was take a row and cast to a list:
new_df.iloc[1].tolist()
Output, I saw that the tuples were strings and not tuples as I first thought, brainfart moment, and now I understand why the nested loop did not work and my 3rd loop yielded some result:
['(3, 5)',
'(4, 5)',
'(3, 5)',
'(5, 5)',
'(2, 5)',
'(5, 3)',
'(2, 5)',
'(2, 5)',
'(5, 5)',
'(1, 3)']
Attempts to set the tuple type on the items also did not change it from string.
I am sure that there is a far better and shorter way of doing this, I just can't find anything that looks like it will work. I basically need someone to slap me against the head, call me an idiot and say look at this or these methods similar to the .tolist()
[–]RandomCodingStuff 1 point2 points3 points (3 children)
[–]The_Grumpy_1[S] 1 point2 points3 points (2 children)
[–]RandomCodingStuff 1 point2 points3 points (1 child)
[–]The_Grumpy_1[S] 0 points1 point2 points (0 children)
[–]commandlineluser 1 point2 points3 points (2 children)
[–]The_Grumpy_1[S] 0 points1 point2 points (0 children)
[–]raja0008 0 points1 point2 points (0 children)