我有一個DataFrame被設置爲使得一列國家名稱被設置爲索引列。我想更改該索引列的標題。這似乎是一件簡單的事情,但我無法找到如何去做。如何做呢?這裏的食品指數如何變成「國家」?如何更改pandas DataFrame的索引列的名稱?
import pandas as pd
df = pd.DataFrame(
[
["alcoholic drinks" , 375, 135, 458, 475],
["beverages" , 57, 47, 53, 73],
["carcase meat" , 245, 267, 242, 227],
["cereals" , 1472, 1494, 1462, 1582],
["cheese" , 105, 66, 103, 103],
["confectionery" , 54, 41, 62, 64],
["fats and oils" , 193, 209, 184, 235],
["fish" , 147, 93, 122, 160],
["fresh fruit" , 1102, 674, 957, 1137],
["fresh potatoes" , 720, 1033, 566, 874],
["fresh Veg" , 253, 143, 171, 265],
["other meat" , 685, 586, 750, 803],
["other veg." , 488, 355, 418, 570],
["processed potatoes", 198, 187, 220, 203],
["processed veg." , 360, 334, 337, 365],
["soft drinks" , 1374, 1506, 1572, 1256],
["sugars" , 156, 139, 147, 175]
],
columns = [
"foods",
"England",
"Northern Ireland",
"Scotland",
"Wales"
]
)
df = df.set_index("foods")
df = df.transpose()
df = df.rename({"foods": "countries"})
df
'rename_axis'的巨大優勢是它會返回一個副本並允許鏈接。 – piRSquared