从数据框列名中删除后缀-Python [英] Removing Suffix From Dataframe Column Names - Python

查看:88
本文介绍了从数据框列名中删除后缀-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to remove a suffix from all columns in a dataframe, however I am getting error messages. Any suggestions would be appreciated.

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

推荐答案

以下是一个更具体的示例:.

Here is a more concrete example:.

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

这篇关于从数据框列名中删除后缀-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆