python : How to rename the column name that changes with the unique value in other column?

标签 python pandas

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

输出:

enter image description here

您还可以使用:

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/

相关文章:

python - 在 RandomForestRegressor 中得到连续不支持的错误

python - 如何解析一个简单的csv文件?

python - 使用列表处理 IndexError 异常

python - Django 本地环境设置

python - 根据不同列的值对数据框执行查找

python - 对重复 ID 使用最高值 (Pandas DataFrame)

python - 如何在 XY/XZ/YZ 平面上绘制 3D 散点数据的投影?

python - 查询数据维度必须与训练数据维度匹配

python - 将多个字段转换为单个字段

pandas - 在fillna中,填充和填充方法有什么区别?