pandas-修改列行名称

pandas-修改列行名称

行和列名全部修改

columns属性

import pandas as pd

df = pd.DataFrame({'a':[1,2,3],
                   'b':[4,5,6],
                   'c':[7,8,9]})
print(df)

#    a  b  c
# 0  1  4  7
# 1  2  5  8
# 2  3  6  9

print(df.columns)
df.columns = ["A", "B", "c"]
print(df.columns)

#Index(['a', 'b', 'c'], dtype='object')
#Index(['A', 'B', 'c'], dtype='object')

index属性

import pandas as pd

df = pd.DataFrame({'a':[1,2,3],
                   'b':[4,5,6],
                   'c':[7,8,9]})

print(df)
print(df.index)
df.index = ["one", "two", "three"]
print(df.index)

#RangeIndex(start=0, stop=3, step=1)
#Index(['one', 'two', 'three'], dtype='object')

列表等的大小(元素数)与行数/列数不一致时,则会发生错误。

 df.index = [1, 2, 3, 4]
# ValueError: Length mismatch: Expected axis has 3 elements, new values have 4 elements
import pandas as pd
import numpy as np

data = np.array([[1, 2, 3, 4, 5],
                 [2, 3, 4, 5, 6],
                 [1, 0, 3, 8, 5]])
df = pd.DataFrame(data)
print(df)

#    0  1  2  3  4
# 0  1  2  3  4  5
# 1  2  3  4  5  6
# 2  1  0  3  8  5


df.index = ['a', 'b', 'c']
df.columns = ['A', 'B', 'C', 'D', 'E']
print(df)

#    A  B  C  D  E
# a  1  2  3  4  5
# b  2  3  4  5  6
# c  1  0  3  8  5

rename函数

任意的行名(index)和列名(columns)的修改

函数DataFrame.rename()可以对任意行和列的名称进行修改。
DataFrame.rename()的参数有index和columns,使用"{旧值:新值}"字典的形式进行参数的指定。

df = pd.DataFrame({'A': [11, 21, 31],
                   'B': [12, 22, 32],
                   'C': [13, 23, 33]},
                  index=['ONE', 'TWO', 'THREE'])

#        A   B   C
#ONE    11  12  13
#TWO    21  22  23
#THREE  31  32  33


df_new = df.rename(columns={'A': 'a'}, index={'ONE': 'one'})
print(df_new)
#         a   B   C
# one    11  12  13
# TWO    21  22  23
# THREE  31  32  33


# 当参数inplace为True时,原DataFrame将会被修改

df_org = df.copy()
df_org.rename(columns={'A': 'a'}, index={'ONE': 'one'}, inplace=True)
print(df_org)
#         a   B   C
# one    11  12  13
# TWO    21  22  23
# THREE  31  32  33

df5 = df.copy()


rename()的参数index和columns值也可以指定为函数方法。

使用lambda表达式和函数进行批处理


df3=df.rename(columns=str.lower, index=str.title)
print(df3)
#         a   b   c
# One    11  12  13
# Two    21  22  23
# Three  31  32  33


df4=df.rename(columns=lambda s: s*3, index=lambda s: s + '!!')
print(df4)
#          AAA  BBB  CCC
# ONE!!     11   12   13
# TWO!!     21   22   23
# THREE!!   31   32   33

rename_axis()

设置索引或列的axis名称。 索引标签(轴标签名称)

DataFrame.rename_axis(self, mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False) 

支持两种调用
(index=index_mapper, columns=columns_mapper, ...)
(mapper, axis={'index', 'columns'}, ...)
import pandas as pd
import numpy as np

df = pd.DataFrame({"num_legs": [4, 4, 2],
                    "num_arms": [0, 0, 2]},
                   ["dog", "cat", "monkey"])
print(df)

#        num_legs  num_arms
#dog            4         0
#cat            4         0
#monkey         2         2

df1 = df.rename_axis("animal")
print(df1)


#        num_legs  num_arms
#animal
#dog            4         0
#cat            4         0
#monkey         2         2

前缀后缀

add_prefix()add_suffix()

import pandas as pd

df = pd.DataFrame({'A': [11, 21, 31],
                   'B': [12, 22, 32],
                   'C': [13, 23, 33]},
                  index=['ONE', 'TWO', 'THREE'])

print(df)
df1 = df.add_prefix("A_",axis=1)
df2 = df.add_prefix("B_",axis=1)

df12 = pd.concat([df1, df2], axis=1)

print(df12)

#        A   B   C
#ONE    11  12  13
#TWO    21  22  23
#THREE  31  32  33
#       A_A  A_B  A_C  B_A  B_B  B_C
#ONE     11   12   13   11   12   13
#TWO     21   22   23   21   22   23
#THREE   31   32   33   31   32   33


df3=df3.add_suffix("_P",axis=0)

print(df3)
#          A   B   C
#ONE_P    11  12  13
#TWO_P    21  22  23
#THREE_P  31  32  33

参考资料

https://www.cnblogs.com/wang_yb/p/17593674.html

https://www.cnblogs.com/BlairGrowing/p/15867390.html

https://www.cjavapy.com/article/722/

posted @ 2023-09-01 23:04  贝壳里的星海  阅读(202)  评论(0编辑  收藏  举报