将多列替换为一列的年份

2024-05-14 00:45:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用世界银行的数据,我试图创建一些表示时间的图表,但我现在拥有的数据如下所示:

enter image description here

因为我不认为有办法把它改成日期时间,所以我认为唯一的办法是用一列名为“Year”的列替换所有这些years列,用我现在在一个单独的列中作为值和当前值的列名。你知道吗

Python中有没有什么好的函数允许这样做,或者我必须遍历整个数据帧?你知道吗

编辑以包含一些代码:

df2 = pd.DataFrame({'Country Name': ['Aruba', 'Afghanistan', 'Angola'],
   'Country Code': ['ABW', 'AFG', 'AGO'],
   '1960':[65.66, 32.29, 33.25],
   '1961': [66.07, 32.74, 33.57],
   '1962': [66.44, 33.18, 33.91], 
   '1963': [66.79, 33.62, 34.27], 
   '1964': [66.11, 34.06, 34.65], 
   '1965': [67.44, 34.49, 35.03]}).set_index('Country Name')

Tags: 数据函数代码name编辑dataframe图表时间
1条回答
网友
1楼 · 发布于 2024-05-14 00:45:30

您可以尝试转置数据帧,这样年值将变成行,然后您可以将其重命名为年,并在绘图中使用它。你知道吗

您可以尝试以下方法:

import pandas as pd
from matplotlib import pyplot as plt

df1 = pd.DataFrame({'Country Name' : ['Aruba', 'Afghanistan', 'Angola'],
   'Country Code' : ['ABW', 'AFG', 'AGO'],
   '1960' : [65.66, 32.29, 33.25],
   '1961' : [66.07, 32.74, 33.57],
   '1962' : [66.44, 33.18, 33.91], 
   '1963' : [66.79, 33.62, 34.27], 
   '1964' : [66.11, 34.06, 34.65], 
   '1965' : [67.44, 34.49, 35.03]})

df2 = df1.transpose()
df2.columns = df1['Country Name']
df2 = df2[2:]
df2['Year'] = df2.index.values

plt.plot(df2['Year'], df2['Aruba'])
plt.plot(df2['Year'], df2['Afghanistan'])
plt.plot(df2['Year'], df2['Angola'])
plt.legend()
plt.show()

输出:Plot Output

相关问题 更多 >