I have the following pandas dataframe df with the first few entries being:
Input Output
0 hj1234 2
1 gu0998 5
2 iu5678 7
3 56h781 11
I need to convert it to 2 separate tuples of lists, looking like this:
my_inputs = [
(h, j, 1, 2, 3, 4),
(g, u, 0, 9, 9, 8),
(i, u, 5, 6, 7, 8),
(5, 6, h, 7, 8, 1)]'
my_outputs =[(2,),
(5,),
(7,),
(11,)]
I have attempted this in excel using the concatenate function however the function has a maximum length to the number of characters that can be concatenated in one line. And so I am trying to do it in python. Kindly assist
If you really want to, this can be done using applymap
and zip
.
a, b = map(list, zip(*df.applymap(lambda x: (x, )).values.tolist()))
a = list(map(tuple, [a_[0] for a_ in a]))
a
# [('h', 'j', '1', '2', '3', '4'),
# ('g', 'u', '0', '9', '9', '8'),
# ('i', 'u', '5', '6', '7', '8'),
# ('5', '6', 'h', '7', '8', '1')]
b
# [(2,), (5,), (7,), (11,)]
Another option is simply handling each column separately.
a = list(map(tuple, df['Input']))
b = [(x, ) for x in df['Output']]
a
# [('h', 'j', '1', '2', '3', '4'),
# ('g', 'u', '0', '9', '9', '8'),
# ('i', 'u', '5', '6', '7', '8'),
# ('5', '6', 'h', '7', '8', '1')]
b
# [(2,), (5,), (7,), (11,)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.