反转一系列列表

Reverse a Series of lists

我有以下 Pandas 个名为 Fruits 的系列:

Out[33]: 
Apples
0    [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, ...
1    [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, ...
2    [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, ...
3                            [0.0, 1.0, 2.0, 3.0, 4.0]
4    [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, ...
5    [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, ...
6    [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, ...
7                            [0.0, 1.0, 2.0, 3.0, 4.0]
8    [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, ...
9             [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]
dtype: object

我想反转每一行(水平)。我正在使用代码 Fruits[::-1] 但输出与索引 Apples(列)相反。反转系列系列的一些想法?

像这样?

    public void foobar() {
        int[][] data = new int[][] {
                { 1, 2, 3, 4, 5 },
                { 1, 2, 3, 4, 5 },
                { 1, 2, 3, 4, 5 },
                { 1, 2, 3, 4, 5 },
                { 1, 2, 3, 4, 5 }
        };

        loop(data);

        System.out.println("=>");

        loopReverse(data);
    }

    public void loop(int[][] data) {
        for(int i=0; i<data.length; i++) {
            System.out.print(i+"\t");
            for(int j=0; j<data[i].length; j++) {
                System.out.print("["+data[i][j] + "] ");
            }
            System.out.println();
        }
    }

    public void loopReverse(int[][] data) {
        for(int i=data.length-1; i >= 0; i--) {
            System.out.print(i+"\t");
            for(int j=data[i].length-1; j >= 0; j--) {
                System.out.print("["+data[i][j] + "] ");
            }
            System.out.println();
        }
    }

您将获得:

0   [1] [2] [3] [4] [5] 
1   [1] [2] [3] [4] [5] 
2   [1] [2] [3] [4] [5] 
3   [1] [2] [3] [4] [5] 
4   [1] [2] [3] [4] [5] 
=>
4   [5] [4] [3] [2] [1] 
3   [5] [4] [3] [2] [1] 
2   [5] [4] [3] [2] [1] 
1   [5] [4] [3] [2] [1] 
0   [5] [4] [3] [2] [1] 
s = pd.Series({0: [0, 1, 2, 3, 4],
 1: [0, 1, 2, 3, 4],
 2: [0, 1, 2, 3, 4],
 3: [0, 1, 2, 3, 4],
 4: [0, 1, 2, 3, 4]})

s.index.name='Apples'

print(s)
Apples
0    [0, 1, 2, 3, 4]
1    [0, 1, 2, 3, 4]
2    [0, 1, 2, 3, 4]
3    [0, 1, 2, 3, 4]
4    [0, 1, 2, 3, 4]
dtype: object

# use apply function to reverse the values row by row.
s.apply(lambda x: x[::-1])
Out[850]: 
Apples
0    [4, 3, 2, 1, 0]
1    [4, 3, 2, 1, 0]
2    [4, 3, 2, 1, 0]
3    [4, 3, 2, 1, 0]
4    [4, 3, 2, 1, 0]
dtype: object

看来你需要str[::-1]:

Fruits = pd.Series(
[[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2],
[0, 1, 2, 3, 4],
[0, 1]]).rename_axis('Apples')
print (Fruits)
Apples
0    [0, 1, 2, 3, 4]
1    [0, 1, 2, 3, 4]
2          [0, 1, 2]
3    [0, 1, 2, 3, 4]
4             [0, 1]
dtype: object

print(Fruits.str[::-1])
Apples
0    [4, 3, 2, 1, 0]
1    [4, 3, 2, 1, 0]
2          [2, 1, 0]
3    [4, 3, 2, 1, 0]
4             [1, 0]
dtype: object