在不更改结构的情况下向数据框列添加后缀
Add suffix to dataframe column without changing the structure
我试图在不触及现有列的情况下向 pandas 数据框的几列添加后缀。我尝试使用以下代码,但它删除了所有其他列:
df_client.iloc[:,-3:].add_suffix('_P1')
我可以将数据框一分为二,重命名第二个数据框的列并将它们合并回去,但我想知道 pandas 中是否有更简单的选项可用。
示例输入:
df:
Name DL PL KH DL PL KH
A 1 1 2 3 4 1
B 1 1 2 3 4 1
预期输出:
df:
Name DL PL KH DL_P1 PL_P1 KH_P1
A 1 1 2 3 4 1
B 1 1 2 3 4 1
没有内置函数,您可以使用自定义函数:
def suffix():
yield ''
i = 0
while True:
i += 1
yield f'_P{i}'
from collections import defaultdict
d = defaultdict(suffix)
df.columns = df.columns.map(lambda x: x+next(d[x]))
输出:
Name DL PL KH DL_P1 PL_P1 KH_P1
0 A 1 1 2 3 4 1
1 B 1 1 2 3 4 1
当您使用 df.columns
时,它会输出一组字符串。这些是列名。
如果您有要更改为的列名列表,假设它名为 new_list
,您可以执行 df.columns = new_list
。这会更改所有列的名称,但不会更改数据。 (必须确保列表的长度相同)
所以只需准备一个新列名列表即可。
new_columns = list(df.columns[:-3]) + [c + "_P1" for c in df.columns[-3:]]
那么就df.columns = new_columns
.
我试图在不触及现有列的情况下向 pandas 数据框的几列添加后缀。我尝试使用以下代码,但它删除了所有其他列:
df_client.iloc[:,-3:].add_suffix('_P1')
我可以将数据框一分为二,重命名第二个数据框的列并将它们合并回去,但我想知道 pandas 中是否有更简单的选项可用。
示例输入: df:
Name DL PL KH DL PL KH
A 1 1 2 3 4 1
B 1 1 2 3 4 1
预期输出: df:
Name DL PL KH DL_P1 PL_P1 KH_P1
A 1 1 2 3 4 1
B 1 1 2 3 4 1
没有内置函数,您可以使用自定义函数:
def suffix():
yield ''
i = 0
while True:
i += 1
yield f'_P{i}'
from collections import defaultdict
d = defaultdict(suffix)
df.columns = df.columns.map(lambda x: x+next(d[x]))
输出:
Name DL PL KH DL_P1 PL_P1 KH_P1
0 A 1 1 2 3 4 1
1 B 1 1 2 3 4 1
当您使用 df.columns
时,它会输出一组字符串。这些是列名。
如果您有要更改为的列名列表,假设它名为 new_list
,您可以执行 df.columns = new_list
。这会更改所有列的名称,但不会更改数据。 (必须确保列表的长度相同)
所以只需准备一个新列名列表即可。
new_columns = list(df.columns[:-3]) + [c + "_P1" for c in df.columns[-3:]]
那么就df.columns = new_columns
.