Python 3.x 从数据帧列名中删除后缀-Python
我试图从数据帧中的所有列中删除后缀,但收到错误消息。如有任何建议,将不胜感激Python 3.x 从数据帧列名中删除后缀-Python,python-3.x,pandas,Python 3.x,Pandas,我试图从数据帧中的所有列中删除后缀,但收到错误消息。如有任何建议,将不胜感激 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[
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
下面是一个更具体的例子:
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
我在接受答案的实现中发现了一个bug。供参考的文件,其中说明: chars参数不是后缀;相反,它的所有值组合都被删除 相反,我不得不使用从我的列名中删除实际的后缀。请参见下面修改的示例
将熊猫作为pd导入
将numpy作为np导入
df=pd.DataFrame(np.random.randint(0,10,size=(10,4)),columns=list('ABCD'))
df=df.添加后缀(“ux”)
df['Ex_']=np.random.randint(0,10,size=(10,1))
df1=pd.DataFrame(df,copy=True)
打印(“带后缀”)
打印(df1.head())
def strip_right(df,后缀=“ux”):
df.columns=df.columns.str.rstrip(后缀)
带右(df1)
打印(“\n\nAfter.rstrip()”)
打印(df1.head())
def replace_right(df,后缀=“ux”):
df.columns=df.columns.str.replace(后缀+'$','',regex=True)
打印(“\n\n带后缀”)
打印(df.head())
更换右(df)
打印(“\n\n在.replace()之后”)
打印(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
df.columns=df.columns.str.rstrip(“'ux')
谢谢你,请发帖回答,这样我可以给你评分。谢谢。使用cols
作为参数,而不是df.columns
(只是为了说明为什么def
会出现语法错误,另一个选项是解决原始问题的最佳选项)@Starbucks这是很好的、愉快的编码方式