Pandas:如何仅重命名 DataFrame 中的最后一列 | 您所在的位置:网站首页 › dataframe重命名某一列 › Pandas:如何仅重命名 DataFrame 中的最后一列 |
Pandas:如何仅重命名 dataframe 中的最后一列经过 本杰明·安德森博
7月 13, 2023
指导
0 条评论 您可以使用以下基本语法仅重命名 pandas DataFrame 的最后一列: df. columns = [*df. columns [:- 1 ], ' new_name ']此特定示例将名为df的 pandas DataFrame 中的最后一列重命名为 new_name 。 以下示例展示了如何在实践中使用此语法。 示例:仅重命名 Pandas 中的最后一列假设我们有以下 pandas DataFrame,其中包含有关各种篮球运动员的信息: import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], ' points ': [18, 22, 19, 14, 14, 11, 20, 28], ' assists ': [5, 7, 7, 9, 12, 9, 9, 4], ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]}) #view DataFrame print (df) team points assists rebounds 0 A 18 5 11 1 B 22 7 8 2 C 19 7 10 3 D 14 9 6 4 E 14 12 6 5 F 11 9 5 6 G 20 9 9 7:28 4 12目前,DataFrame 的最后一列名为ounces 。 我们可以使用以下语法将此列重命名为rebs : #rename last column to 'rebs' df. columns = [*df. columns [:- 1 ], ' rebs '] #view updated DataFrame print (df) team points assists rebs 0 A 18 5 11 1 B 22 7 8 2 C 19 7 10 3 D 14 9 6 4 E 14 12 6 5 F 11 9 5 6 G 20 9 9 7:28 4 12请注意,最后一列已重命名为 rebs ,所有其他列保持不变。 我们还可以使用以下语法来显示 DataFrame 中所有列名称的列表: #view column names print ( df.columns ) Index(['team', 'points', 'assists', 'rebs'], dtype='object')我们看到最后一列已重命名为rebs 。 使用这种语法的优点是我们不需要提前知道DataFrame中有多少列。 其他资源以下教程解释了如何在 pandas 中执行其他常见操作: 如何列出 Pandas 中的所有列名称如何在 Pandas 中按名称对列进行排序如何删除 Pandas 中的重复列 关于作者本杰明·安德森博大家好,我是本杰明,一位退休的统计学教授,后来成为 Statorials 的热心教师。 凭借在统计领域的丰富经验和专业知识,我渴望分享我的知识,通过 Statorials 增强学生的能力。了解更多 添加评论取消回复 |
CopyRight 2018-2019 实验室设备网 版权所有 |