Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何一次性重命名pandas dataframe中的多个列?_Python 3.x_Pandas_Dataframe - Fatal编程技术网

Python 3.x 如何一次性重命名pandas dataframe中的多个列?

Python 3.x 如何一次性重命名pandas dataframe中的多个列?,python-3.x,pandas,dataframe,Python 3.x,Pandas,Dataframe,我有一个数据框,如: _Ab _Bc C D _Ef _Fg 0 a 4 7 1 5 a 1 b 5 8 3 3 a 2 c 4 9 5 6 a 3 d 5 4 7 9 b 4 e 5 2 1 2 b 5 f 4 3 0 4 b 我想删除某些列名中的起始。。显然,我可以

我有一个数据框,如:

   _Ab  _Bc   C    D   _Ef  _Fg
0   a    4    7    1    5    a
1   b    5    8    3    3    a
2   c    4    9    5    6    a
3   d    5    4    7    9    b
4   e    5    2    1    2    b
5   f    4    3    0    4    b

我想删除某些列名中的起始
。显然,我可以一次替换一个,但这将是非常低效的,因为我有很多列。那么我如何才能有效地做到这一点呢?

将列表理解与
if-else
startswith
结合使用:

df.columns = [x.lstrip('_') if x.startswith('_') else x for x in df.columns]
另一种解决方案尝试从所有列中左剥离
\uuu

df.columns = [x.lstrip('_') for x in df.columns]
或与:

或使用
重命名

df = df.rename(columns=lambda x: x.lstrip('_'))
print (df)
  Ab  Bc  C  D  Ef Fg
0  a   4  7  1   5  a
1  b   5  8  3   3  a
2  c   4  9  5   6  a
3  d   5  4  7   9  b
4  e   5  2  1   2  b
5  f   4  3  0   4  b

将列表理解与
if-else
startswith
一起使用:

df.columns = [x.lstrip('_') if x.startswith('_') else x for x in df.columns]
另一种解决方案尝试从所有列中左剥离
\uuu

df.columns = [x.lstrip('_') for x in df.columns]
或与:

或使用
重命名

df = df.rename(columns=lambda x: x.lstrip('_'))
print (df)
  Ab  Bc  C  D  Ef Fg
0  a   4  7  1   5  a
1  b   5  8  3   3  a
2  c   4  9  5   6  a
3  d   5  4  7   9  b
4  e   5  2  1   2  b
5  f   4  3  0   4  b

这应该适合您:

df.columns=[c.lstrip(“”)表示df.columns中的c]

这应该适合您:

df.columns=[c.lstrip(“”)表示df.columns中的c]

列数是多少?列数是多少?尝试了您的代码,但我得到了以下错误:AttributeError:'Index'对象没有属性'strip'@Ank-您是否尝试
df.columns=df.columns.lstrip('')
而不是
df.columns=df.columns.str.lstrip('')
-缺少
str
?现在我得到AttributeError:“Index”对象没有属性“lstrip”。您无法键入StringMethods访问器。不要写
df.columns.lstrip(.)
write
df.columns.str.lstrip(.)
(方法调用中的句号代表各种参数)@Ank-第一个解决方案如何工作
df.columns=[x.lstrip(“'),如果x.startswith(“'),否则x代表df.columns中的x]
?尝试了你的代码,但是我得到了这个错误:AttributeError:'Index'对象没有属性'strip'@Ank-您是否尝试
df.columns=df.columns.lstrip('''')
而不是
df.columns=df.columns.str.lstrip(''')
-缺少
str
?现在我得到AttributeError:“Index”对象没有属性“lstrip”。您无法键入StringMethods访问器。而不是写
df.columns.lstrip(.)
write
df.columns.str.lstrip(.)
(方法调用中的句号代表各种参数)@Ank-第一个解决方案如何工作
df.columns=[x.lstrip(''),如果x.startswith(''u'),否则x代表df.columns中的x]