gpt4 book ai didi

python - 如何通过传递参数来重新排列数据框中的列

转载 作者:行者123 更新时间:2023-12-01 00:36:41 25 4
gpt4 key购买 nike

我有以下列表

('EmpId', 'EMpName', 'Age', 'SerialNo')

我想将 Age,SerialNo 放在起始位置,其余列如下

ColumnsToRearrange = ['年龄', '序列号']

通过对数据帧内的列进行硬编码,我可以实现如下所示。我是否有可能将其作为参数传递

df = df[['Age', 'SerialNo'] + [col for col in df.columns if col not in ['Age', 'SerialNo']]] 

但我想将其作为参数传递

df = df[Header + [col for col in df.columns if col not in Header]] 

我收到以下错误消息

Error:TypeError: can only concatenate tuple (not "list") to tuple

最佳答案

下面是对 DataFrame 的列进行重新排序的四种方法

import pandas as pd
df =pd.DataFrame({'EmpId':[1,2,3,4],'EMpName':[2,4,6,8],'Age':[3,7,6,8],'SerialNo':[2,4,8,2]})
"""
EmpId EMpName Age SerialNo
0 1 2 3 2
1 2 4 7 4
2 3 6 6 8
3 4 8 8 2
"""

Original- ('EmpId', 'EMpName', 'Age', 'SerialNo')
Output - ('Age', 'SerialNo','EmpId', 'EMpName')

两列交换

cols = list(df.columns)
a, b = cols.index('EmpId'), cols.index('Age')
cols[b], cols[a] = cols[a], cols[b]
df = df[cols]

重新排序列交换(2 次交换)

cols = list(df.columns)
a, b, c, d = cols.index('EmpId'), cols.index('Age'), cols.index('EMpName'), cols.index('SerialNo')
cols[a], cols[b], cols[c], cols[d] = cols[b], cols[a], cols[d], cols[c]
df = df[cols]

交换多个现在归结为如何使用列表切片 -

cols = list(df.columns)
colss = cols[2:] + cols[:2]
df = df[colss]
seq_list=['Age', 'SerialNo']

创建函数

def set_column_sequence(dataframe, seq, front=True):
'''Takes a dataframe and a subsequence of its columns,
returns dataframe with seq as first columns if "front" is True,
and seq as last columns if "front" is False.
'''
cols = seq[:] # copy so we don't mutate seq
for x in dataframe.columns:
if x not in cols:
if front: #we want "seq" to be in the front
#so append current column to the end of the list
cols.append(x)
else:
#we want "seq" to be last, so insert this
#column in the front of the new column list
#"cols" we are building:
cols.insert(0, x)
return dataframe[cols]
q=set_column_sequence(df,seq_list)

关于python - 如何通过传递参数来重新排列数据框中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57687834/

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