[英]add_suffix to column name based on position
I have a dataset where I want to add a suffix to column names based on their positions. 我有一个数据集,我想根据列的位置向列名添加后缀。 For ex- 1st to 4th columns should be named 'abc_1', then 5th to 8th columns as 'abc_2' and so on. 对于第1至第4列,应将其命名为“ abc_1”,然后将第5至第8列命名为“ abc_2”,依此类推。
I have tried using dataframe.rename
我尝试使用dataframe.rename
but it is a time consuming process. 但这是一个耗时的过程。 What would be the most efficient way to achieve this? 实现这一目标的最有效方法是什么?
I think here is good choice create MultiIndex
for avoid duplicated columns names - create first level by floor divide by 4
and add prefix by f-string
s: 我认为这是一个很好的选择,创建MultiIndex
以避免出现重复的列名-按地板除以4
创建第一级,并按f-string
添加前缀:
np.random.seed(123)
df = pd.DataFrame(np.random.randint(10, size=(5, 10)))
df.columns = [[f'abc_{i+1}' for i in df.columns // 4], df.columns]
print (df)
abc_1 abc_2 abc_3
0 1 2 3 4 5 6 7 8 9
0 2 2 6 1 3 9 6 1 0 1
1 9 0 0 9 3 4 0 0 4 1
2 7 3 2 4 7 2 4 8 0 7
3 9 3 4 6 1 5 6 2 1 8
4 3 5 0 2 6 2 4 4 6 3
More general solution if no RangeIndex
in column names: 如果列名称中没有RangeIndex
,则可以使用更通用的解决方案:
cols = [f'abc_{i+1}' for i in np.arange(len(df.columns)) // 4]
df.columns = [cols, df.columns]
print (df)
abc_1 abc_2 abc_3
0 1 2 3 4 5 6 7 8 9
0 2 2 6 1 3 9 6 1 0 1
1 9 0 0 9 3 4 0 0 4 1
2 7 3 2 4 7 2 4 8 0 7
3 9 3 4 6 1 5 6 2 1 8
4 3 5 0 2 6 2 4 4 6 3
Also is possible specify MultiIndex levels names by MultiIndex.from_arrays
: 也可以通过MultiIndex.from_arrays
指定MultiIndex级别名称:
df.columns = pd.MultiIndex.from_arrays([cols, df.columns], names=('level0','level1'))
print (df)
level0 abc_1 abc_2 abc_3
level1 0 1 2 3 4 5 6 7 8 9
0 2 2 6 1 3 9 6 1 0 1
1 9 0 0 9 3 4 0 0 4 1
2 7 3 2 4 7 2 4 8 0 7
3 9 3 4 6 1 5 6 2 1 8
4 3 5 0 2 6 2 4 4 6 3
Then is possible select each level by xs
: 然后可以通过xs
选择每个级别:
print (df.xs('abc_2', axis=1))
4 5 6 7
0 3 9 6 1
1 3 4 0 0
2 7 2 4 8
3 1 5 6 2
4 6 2 4 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.