gpt4 book ai didi

python - 用 Pandas : Is there an equivalent to dplyr's select(. ..,一切())重新排列列?

转载 作者:行者123 更新时间:2023-12-03 16:36:40 25 4
gpt4 key购买 nike

我正在尝试重新排列 DataFrame 中的列,首先放置几列,然后放置所有其他列。

与R的dplyr ,这看起来像:

library(dplyr)

df = tibble(col1 = c("a", "b", "c"),
id = c(1, 2, 3),
col2 = c(2, 4, 6),
date = c("1 Feb", "2 Feb", "3 Feb"))

df2 = select(df,
id, date, everything())

简单。使用 Python 的 pandas ,这是我尝试过的:

import pandas as pd

df = pd.DataFrame({
"col1": ["a", "b", "c"],
"id": [1, 2, 3],
"col2": [2, 4, 6],
"date": ["1 Feb", "2 Feb", "3 Feb"]
})

# using sets
cols = df.columns.tolist()
cols_1st = {"id", "date"}
cols = set(cols) - cols_1st
cols = list(cols_1st) + list(cols)

# wrong column order
df2 = df[cols]

# using lists
cols = df.columns.tolist()
cols_1st = ["id", "date"]
cols = [c for c in cols if c not in cols_1st]
cols = cols_1st + cols

# right column order, but is there a better way?
df3 = df[cols]
pandas方式更乏味,但我对此相当陌生。有没有更好的办法?

最佳答案

您可以使用 df.drop :

>>> df = pd.DataFrame({
"col1": ["a", "b", "c"],
"id": [1, 2, 3],
"col2": [2, 4, 6],
"date": ["1 Feb", "2 Feb", "3 Feb"]
})

>>> df

col1 id col2 date
0 a 1 2 1 Feb
1 b 2 4 2 Feb
2 c 3 6 3 Feb

>>> cols_1st = ["id", "date"]

>>> df[cols_1st + list(df.drop(cols_1st, 1))]

id date col1 col2
0 1 1 Feb a 2
1 2 2 Feb b 4
2 3 3 Feb c 6

关于python - 用 Pandas : Is there an equivalent to dplyr's select(. ..,一切())重新排列列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60478373/

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