1

I have a dataframe with a column that is a filled with different lists. I want to reverse every list in the column.

Example of what I want:

I want this df:

 index       x_val
 1           [1,2,3,4,5]
 2           [2,3,4,5,6]

to become this:

 index       x_val
 1           [5,4,3,2,1]
 2           [6,5,4,3,2]

I tried the following code:

 df['x_val'] = df['x_val'].apply(lambda x: x.reverse())

and I got this:

 index       x_val
 1           nan
 2           nan

What am I doing wrong?

smci
  • 32,567
  • 20
  • 113
  • 146
  • 2
    `.reverse()` returns `None`, of course – juanpa.arrivillaga May 31 '21 at 00:22
  • Does this answer your question? [How can I reverse a list in Python?](https://stackoverflow.com/questions/3940128/how-can-i-reverse-a-list-in-python) – smci May 31 '21 at 02:16
  • You said your column is list (not string). So just `apply(..., axis=1)` a lambda function that calls `reversed(x)` on your list x. (Don't try to use `x.reverse()`, because that's a function that works in-place. – smci May 31 '21 at 02:22

2 Answers2

1

Two Cases:

Case 1

If List is of int type forming the object type column x_val

df = pd.DataFrame({
    'index':[1,2],
    'x_val':[[1,2,3,4,5], [2,3,4,5,6]]
})

Code

df['x_val'] = df['x_val'].apply(lambda x: list(reversed(x)))
df

Case 2

If x_val column is of object of str type. (Will work with single character strings, if in practice string is of multi-char then consider converting it to list of ints and then use code of case 1).

d="""index|x_val
1|[1,2,3,4,5]
2|[2,3,4,5,6]"""
df=pd.read_csv(StringIO(d), sep='|', engine='python')

Code

df['x_val'] = df['x_val'].apply(lambda x: '['+x[-2:0:-1]+']')
df

Output

    index   x_val
0   1       [5,4,3,2,1]
1   2       [6,5,4,3,2]
Utsav
  • 5,572
  • 2
  • 29
  • 43
0

@Uts is exactly right for Case 1. For Case 2, any 2-digit (or more) numbers will be transposed because they are treated as strings instead of delimited integer values that are represented as strings.

Please see Case 2b below for splitting and reversing the list of integers represented as strings.

import pandas as pd

print('Case 1 - x_val = lists of int')
df = pd.DataFrame({
     'index':[1,2,3],
     'x_val':[[1,2,3,4,5], [2,3,4,5,6], [6,7,8,9,10]]
})
print(df)
df['x_val'] = df['x_val'].apply(lambda x: list(reversed(x)))
print(df)

print('\nCase 2 - x_val = strings, string values will be reversed')
df = pd.DataFrame({
    'index':[1,2,3],
    'x_val':['[1,2,3,4,5]', '[2,3,4,5,6]', '[6,7,8,9,10]']
})
print(df)
df['x_val'] = df['x_val'].apply(lambda x: '['+x[-2:0:-1]+']')
print(df)

print('\nCase 2b - x_val = strings')
df = pd.DataFrame({
    'index':[1,2,3],
    'x_val':['[1,2,3,4,5]', '[2,3,4,5,6]', '[6,7,8,9,10]']
})
print(df)
df['x_val'] = df['x_val'].apply(lambda x: '['+','.join(el for el in 
    reversed(x[1:-1].split(',')))+']')
print(df)

Output:

Case 1 - x_val = lists of int
   index             x_val
0      1   [1, 2, 3, 4, 5]
1      2   [2, 3, 4, 5, 6]
2      3  [6, 7, 8, 9, 10]
   index             x_val
0      1   [5, 4, 3, 2, 1]
1      2   [6, 5, 4, 3, 2]
2      3  [10, 9, 8, 7, 6]

Case 2 - x_val = strings, string values will be reversed
   index         x_val
0      1   [1,2,3,4,5]
1      2   [2,3,4,5,6]
2      3  [6,7,8,9,10]
   index         x_val
0      1   [5,4,3,2,1]
1      2   [6,5,4,3,2]
2      3  [01,9,8,7,6]

Case 2b - x_val = strings
   index         x_val
0      1   [1,2,3,4,5]
1      2   [2,3,4,5,6]
2      3  [6,7,8,9,10]
   index         x_val
0      1   [5,4,3,2,1]
1      2   [6,5,4,3,2]
2      3  [10,9,8,7,6]
BalooRM
  • 434
  • 1
  • 6
  • 15
  • Case 2b can also be written as: df['x_val'] = df['x_val'].apply(lambda x: '['+','.join(el for el in x[1:-1].split(',')[::-1])+']') – BalooRM May 31 '21 at 01:59