data = {'pop': [2.0, 3.0, 4.0],'county':['jpy','jpy','jpy']}
df = pd.DataFrame(data)
我想使用其他列中的唯一值动态更改列('pop')名称。我不想对列值进行硬编码。我正在尝试类似下面的方法,但它抛出了一个错误。
value = df.county.unique()
df.rename(columns={'pop': str(value)}, inplace=True)
预期输出:
df = jpy county
2.0 jpy
3.0 jpy
4.0 jpy
最佳答案
根据给定的数据,您可以使用:
df.rename(columns={'pop': str(*value)}, inplace=True)
您将把value
中唯一的元素转换为str
输出:
您还可以使用:
df.rename(columns={'pop': list(value)[0]}, inplace=True)
关于 python : How to rename the column name that changes with the unique value in other column?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60935476/