我有一个像这样的数据框:
0 1 2 3 4 ... 37 38 39 40 41
0 26.265 0.072 27.925 3.011 4.541 ... 7.812 16.954 0.000 1 nan
0 26.265 0.072 27.901 3.015 4.541 ... 7.773 16.954 0.000 1 nan
0 26.265 0.072 27.925 3.011 4.541 ... 7.773 17.032 0.000 1 nan
0 26.265 0.072 27.901 3.012 4.541 ... 7.773 16.954 0.000 1 nan
0 26.265 0.072 27.901 3.015 4.541 ... 7.773 17.032 0.000 1 nan
.. ... ... ... ... ... ... ... ... ... .. ...
0 26.241 0.072 27.901 3.013 4.541 ... 7.773 17.032 0.000 1 nan
0 26.265 0.072 27.925 3.012 4.541 ... 7.773 16.954 0.000 1 nan
0 26.265 0.073 27.901 3.012 4.541 ... 7.812 16.954 0.000 1 nan
0 26.265 0.072 27.901 3.016 4.541 ... 7.773 16.954 0.000 1 nan
0 26.265 0.072 27.901 3.012 4.541 ... 7.773 17.032 0.000 1 nan
我想重命名每获得2个列的列:
2 3 4 5 6 ... 39 40 41 42 43
0 26.265 0.072 27.925 3.011 4.541 ... 7.812 16.954 0.000 1 nan
0 26.265 0.072 27.901 3.015 4.541 ... 7.773 16.954 0.000 1 nan
0 26.265 0.072 27.925 3.011 4.541 ... 7.773 17.032 0.000 1 nan
0 26.265 0.072 27.901 3.012 4.541 ... 7.773 16.954 0.000 1 nan
0 26.265 0.072 27.901 3.015 4.541 ... 7.773 17.032 0.000 1 nan
.. ... ... ... ... ... ... ... ... ... .. ...
0 26.241 0.072 27.901 3.013 4.541 ... 7.773 17.032 0.000 1 nan
0 26.265 0.072 27.925 3.012 4.541 ... 7.773 16.954 0.000 1 nan
0 26.265 0.073 27.901 3.012 4.541 ... 7.812 16.954 0.000 1 nan
0 26.265 0.072 27.901 3.016 4.541 ... 7.773 16.954 0.000 1 nan
0 26.265 0.072 27.901 3.012 4.541 ... 7.773 17.032 0.000 1 nan
我是以这种方式完成的:
data.rename(columns={41:43,40:42,39:41,38:40,37:39,36:38,35:37,34:36,33:35,32:34,31:33,30:32,29:31...})
但是我在哪里徘徊呢?
谢谢
答案 0 :(得分:4)
您也可以直接在列上工作:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>${thymeleaf-extras-springsecurity5.version}</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
<version>${thymeleaf-extras-java8time.version}</version>
</dependency>
<dependency>
<groupId>io.github.jpenren</groupId>
<artifactId>thymeleaf-spring-data-dialect</artifactId>
<version>${thymeleaf-spring-data-dialect.version}</version>
</dependency>
<dependency
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
答案 1 :(得分:3)
您可以使用列表推导对列进行重命名,以在每个列名称中添加两个(如果列名称是字符串,但它们看起来像是整数,则我使用int
):
data.columns = [int(col) + 2 for col in data.columns]
如果列已经是整数,则:
data.columns = [col + 2 for col in data.columns]
答案 2 :(得分:1)
您仍然可以使用rename
方法(通过该方法,您可以在此之上链接其他方法)。只需传递一个代替字典的函数即可:
new_df = df.rename(columns=lambda c: int(c) + 2)
如果列名已经是数字,则可以删除int()
并执行:
new_df = df.rename(columns=lambda c: c + 2)
最后,对于“为什么不能这么做”答案,您可以抛弃lambda并使用__add__
dunder方法,如下所示:
new_df = df.rename(columns=int(2).__add__)
答案 3 :(得分:0)
您可以使用范围:
df.columns = list(range(2,len(df.columns)+2))