pandas 将DataFrame中的系列反转为新列[重复]

sr4lhrrt  于 2023-09-29  发布在  其他
关注(0)|答案(4)|浏览(96)

此问题已在此处有答案

Reverse DataFrame Column, But Maintain the Index(2个答案)
4天前关闭。
如何将DataFrame中的序列顺序反转到新列中?

data = [["US Dollar", 7.00],
        ['Euro', 2.00],
        ['British Pound', 4.00],
        ['Indian Rupee', 2.00],
        ['Australian Dollar', 9.00],
        ['Canadian Dollar', 3.00],
        ['Singapore Dollar', 3.00],
        ['Swiss Franc', 5.00]
       ]

df = pd.DataFrame(data, columns=['Currency', 'Order'])

我试着用loc来做这个,但那是给我同样的命令回来。

df['Reverse Order'] = df['Order'].iloc[::-1]
df

#   Currency            Order   Reverse Order
# 0 US Dollar           7.0     7.0
# 1 Euro                2.0     2.0
# 2 British Pound       4.0     4.0
# 3 Indian Rupee        2.0     2.0
# 4 Australian Dollar   9.0     9.0
# 5 Canadian Dollar     3.0     3.0
# 6 Singapore Dollar    3.0     3.0
# 7 Swiss Franc         5.0     5.0

我想得到相反的顺序

#   Currency            Order   Reverse Order
# 0 US Dollar           7.0     5.0
# 1 Euro                2.0     3.0
# 2 British Pound       4.0     3.0
# 3 Indian Rupee        2.0     9.0
# 4 Australian Dollar   9.0     2.0
# 5 Canadian Dollar     3.0     4.0
# 6 Singapore Dollar    3.0     2.0
# 7 Swiss Franc         5.0     7.0
daupos2t

daupos2t1#

将值转换为numpy数组(因为现在索引重新对齐到原始数组):

df["Reverse Order"] = df.loc[::-1, "Order"].to_numpy()
print(df)

图纸:

Currency  Order  Reverse Order
0          US Dollar    7.0            5.0
1               Euro    2.0            3.0
2      British Pound    4.0            3.0
3       Indian Rupee    2.0            9.0
4  Australian Dollar    9.0            2.0
5    Canadian Dollar    3.0            4.0
6   Singapore Dollar    3.0            2.0
7        Swiss Franc    5.0            7.0
yks3o0rb

yks3o0rb2#

使用values给出numpy数组
用这个就能得到结果

df['Reverse Order'] = df['Order'].values[::-1]
print(df)
Currency  Order  Reverse Order
0          US Dollar    7.0            5.0
1               Euro    2.0            3.0
2      British Pound    4.0            3.0
3       Indian Rupee    2.0            9.0
4  Australian Dollar    9.0            2.0
5    Canadian Dollar    3.0            4.0
6   Singapore Dollar    3.0            2.0
7        Swiss Franc    5.0            7.0
2exbekwf

2exbekwf3#

df['Order'].iloc[::-1]创建一个仍具有原始索引的Series。Pandas在将Series分配给嵌套框架中的列时会遵循索引。你可以在赋值前删除索引以使其工作:

df['Reverse Order'] = df['Order'].iloc[::-1].reset_index(drop=True)
0mkxixxg

0mkxixxg4#

若要修复此问题,请在将反转序列分配给新列之前重置该序列的索引。这样,秩序就得以维持。

df['Reverse Order'] = df['Order'].iloc[::-1].reset_index(drop=True)
print(df)

下面是输出:

Currency  Order  Reverse Order
0         US Dollar    7.0            5.0
1              Euro    2.0            3.0
2     British Pound    4.0            3.0
3      Indian Rupee    2.0            9.0
4 Australian Dollar    9.0            2.0
5   Canadian Dollar    3.0            4.0
6  Singapore Dollar    3.0            2.0
7       Swiss Franc    5.0            7.0

相关问题