反转一系列列表

2024-04-19 18:39:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下熊猫系列叫做水果:

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(列)相反。有什么想法可以把系列颠倒过来?你知道吗


Tags: 代码objectoutdtypefruitsapples水果
3条回答

似乎你需要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

像这样?你知道吗

    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

相关问题 更多 >