Pandas make columns to rows
Question:
Answers:
you need to use the melt method, something like this
df2 = df.melt(id_vars=['country','continent'], var_name="year", value_vars=[str(x) for x in range(1850,2011)])
A different approach.
For this to work you need to have all "name" columns as index.
Here is a sample if you only have Country and values.
df = pd.DataFrame({
"Country": ["China", "Lithuania"],
"2000": [2,10],
"2022": [10,44],
})
df.set_index("Country").stack()
Results in
Country
China 2000 2
2022 10
Lithuania 2000 10
2022 44
dtype: int64
you need to use the melt method, something like this
df2 = df.melt(id_vars=['country','continent'], var_name="year", value_vars=[str(x) for x in range(1850,2011)])
A different approach.
For this to work you need to have all "name" columns as index.
Here is a sample if you only have Country and values.
df = pd.DataFrame({
"Country": ["China", "Lithuania"],
"2000": [2,10],
"2022": [10,44],
})
df.set_index("Country").stack()
Results in
Country
China 2000 2
2022 10
Lithuania 2000 10
2022 44
dtype: int64