【问题标题】:Removing Suffix From Dataframe Column Names - Python从数据框列名称中删除后缀 - Python
【发布时间】:2019-06-03 11:15:56
【问题描述】:

我正在尝试从数据框中的所有列中删除后缀,但是我收到了错误消息。任何建议,将不胜感激。

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

【问题讨论】:

  • df.columns=df.columns.str.rstrip('_x')
  • 谢谢,请发帖作为答案,以便我给予信任。谢谢。
  • 使用cols 作为参数而不是df.columns(只是为了说明为什么你的def 给出了一个语法错误,另一个选项是解决你原来问题的最佳选择)
  • @Starbucks 很好,编码愉快

标签: python-3.x pandas


【解决方案1】:

这是一个更具体的例子:

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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      相关资源
      最近更新 更多