gpt4 book ai didi

python - Pandas - 按列排序

转载 作者:太空宇宙 更新时间:2023-11-03 10:55:48 25 4
gpt4 key购买 nike

我有一个名为“df”的 Pandas 数据框:

  x y
0 1 2
1 2 4
2 3 8

我将它分成两帧,然后尝试合并回去:

df_1 = df[df['x']==1]  
df_2 = df[df['x']!=1]

我的目标是以相同的顺序恢复它,但是当我连接时,我得到以下信息:

frames = [df_1, df_2]
solution = pd.concat(frames)
solution.sort_values(by='x', inplace=False)

x y
1 2 4
2 3 8
0 1 2

问题是我需要“x”值以我提取的相同顺序返回到新数据框中。有解决办法吗?

最佳答案

使用 .loc 指定您想要的顺序。选择原始索引。

solution.loc[df.index]

或者,如果您信任每个组件中的索引值,那么

solution.sort_index()

enter image description here

设置

df = pd.DataFrame([[1, 2], [2, 4], [3, 8]], columns=['x', 'y'])

df_1 = df[df['x']==1]
df_2 = df[df['x']!=1]

frames = [df_1, df_2]
solution = pd.concat(frames)

关于python - Pandas - 按列排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41192805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com