从数据框列名中删除后缀 - Python

4
我正在尝试从数据框的所有列中删除后缀,但是我收到了错误消息。如果有建议,将不胜感激。
df = pd.DataFrame(np.random.randint(0,10,size=(10, 4)), columns=list('ABCD'))
df.add_suffix('_x')

def strip_right(df.columns, _x):
    if not text.endswith("_x"):
        return text
    # else
    return text[:len(df.columns)-len("_x")]

错误:

def strip_right(tmp, "_x"):
                            ^
SyntaxError: invalid syntax

我也尝试过去除引号。

def strip_right(df.columns, _x):
    if not text.endswith(_x):
        return text
    # else
    return text[:len(df.columns)-len(_x)]

错误:

def strip_right(df.columns, _x):
                      ^
SyntaxError: invalid syntax

3
将DataFrame的列名末尾的下划线字符去除:df.columns=df.columns.str.rstrip('_x') - BENY
谢谢, 请将翻译后的文本作为答案发布,这样我就可以给予认可。谢谢。 - Starbucks
使用cols作为参数而不是df.columns(仅为了展示为什么您的def会产生语法错误,另一种选择是解决您原始问题的最佳选择)。 - Jondiedoop
@Starbucks 没问题,愉快编码。 - BENY
3个回答

7
这里是一个更具体的例子:。
import pandas as pd
import numpy as np
    
df = pd.DataFrame(np.random.randint(0,10,size=(10, 4)), columns=list("ABCD"))
df = df.add_suffix("_x")
    
print("With Suffix")
print(df.head())
    
def strip_right(df, suffix="_x"):
    df.columns = df.columns.str.rstrip(suffix)
  
strip_right(df) 
    
print("\n\nWithout Suffix")
print(df.head())

输出:

With Suffix
   A_x  B_x  C_x  D_x
0    0    7    0    2
1    5    1    8    5
2    6    2    0    1
3    6    6    5    6
4    8    6    5    8
    
    
Without Suffix
   A  B  C  D
0  0  7  0  2
1  5  1  8  5
2  6  2  0  1
3  6  6  5  6
4  8  6  5  8

2
我发现已接受答案的实现中存在一个错误。pandas.Series.str.rstrip()文档引用了 str.rstrip(),其中指出:

"chars参数不是后缀; 相反,它的所有值的组合都将被剥离。"

相反,我必须使用pandas.Series.str.replace 来从我的列名中删除实际的后缀。请参见以下修改后的示例。

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0,10,size=(10, 4)), columns=list('ABCD'))
df = df.add_suffix('_x')
df['Ex_'] = np.random.randint(0,10,size=(10, 1))

df1 = pd.DataFrame(df, copy=True)
print ("With Suffix")
print(df1.head())

def strip_right(df, suffix='_x'):
    df.columns = df.columns.str.rstrip(suffix)

strip_right(df1) 

print ("\n\nAfter .rstrip()")
print(df1.head())

def replace_right(df, suffix='_x'):
    df.columns = df.columns.str.replace(suffix+'$', '', regex=True)

print ("\n\nWith Suffix")
print(df.head())

replace_right(df)

print ("\n\nAfter .replace()")
print(df.head())

输出:

With Suffix
   A_x  B_x  C_x  D_x  Ex_
0    4    9    2    3    4
1    1    6    5    8    6
2    2    5    2    3    6
3    1    4    7    6    4
4    3    9    3    5    8


After .rstrip()
   A  B  C  D  E
0  4  9  2  3  4
1  1  6  5  8  6
2  2  5  2  3  6
3  1  4  7  6  4
4  3  9  3  5  8


After .replace()
   A  B  C  D  Ex_
0  4  9  2  3    4
1  1  6  5  8    6
2  2  5  2  3    6
3  1  4  7  6    4
4  3  9  3  5    8

1

正如@rcodemonkey所指出的那样,被接受的答案是不正确的。在某些情况下,它会删除字符串末尾的其他字符,因为str.rstrip方法的to_strip参数实际上是一组字符,而不是一个正确的后缀。

因此,您应该使用其他提议的解决方案(str.replace方法),或者我建议使用str.removesuffix方法(从python 3.9和pandas 1.4开始提供),这是这些解决方案中最清晰和最易于理解的方法:

def remove_suffix(df, suffix='_x'):
    df.columns = df.columns.str.removesuffix(suffix)

完整示例(采用已接受答案中的示例):

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0,10,size=(10, 4)), columns=list('ABCD'))
df = df.add_suffix('_x')

# With Suffix
#    A_x  B_x  C_x  D_x
# 0    5    4    7    4
# 1    9    6    4    6
# 2    1    3    2    9
# 3    3    3    1    3
# 4    0    0    6    2

remove_suffix(df) 

# Without Suffix
#    A  B  C  D
# 0  5  4  7  4
# 1  9  6  4  6
# 2  1  3  2  9
# 3  3  3  1  3
# 4  0  0  6  2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接