python - 根据 python 数据框中的条件重命名列

标签 python dataframe pyspark

我在 python 数据框中有一列,它将是 _00_test00_test 。我想重命名要测试的列。

我想要做的是检查数据框中的列,如果存在 _00_test00_test ,然后将列名称重命名为 test

如何做到这一点?

最佳答案

如果该列不在数据框中,

DataFrame.rename 不会失败。因此,如果我们假设排他性,则数据框中只能存在一列,那么您可以一次性完成此操作::

>>> import pandas as pd
>>> df = pd.DataFrame({'_00_test': range(5)})
>>> df
   _00_test
0         0
1         1
2         2
3         3
4         4
>>> df.rename(columns={'_00_test': 'test', '00_test': 'test'})
   test
0     0
1     1
2     2
3     3
4     4

关于python - 根据 python 数据框中的条件重命名列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42821288/

相关文章:

sql - 如何在 pyspark 的 postgres jdbc 驱动程序中使用 nextval()?

Pyspark Dataframe 将函数应用于两列

python - 类型错误 : count() takes exactly one argument

python - Pandas 从现有列添加列 based_domain

python - 在循环中评估 Tensorflow 操作非常慢

将 "flipped"表正确读入 data.frame

python - rpy2 转换矩阵 -> DataFrame

apache-spark - 首先,我可以定义比可用内核更多的执行程序吗?

python - 在没有已知函数的情况下将数据拟合到曲线

python - 操作系统错误 : [Errno 2] No such file or directory - code worked on new computer doesnt work on old one