Python 熊猫数据帧可以';t从CSV绘制x值

Python 熊猫数据帧可以';t从CSV绘制x值,python,pandas,dataframe,matplotlib,Python,Pandas,Dataframe,Matplotlib,我试图从CSV文件将年度数据读入Pandas数据框,但它没有正确读取年份。我认为问题是我必须转换行和列 这里有一个简单的例子来说明这个问题 from io import StringIO import matplotlib.pyplot as plt import pandas as pd import seaborn as sn # This is what I wish I had. csv_source1 = StringIO("""\ year,Apples,Bananas,Cher

我试图从CSV文件将年度数据读入Pandas数据框,但它没有正确读取年份。我认为问题是我必须转换行和列

这里有一个简单的例子来说明这个问题

from io import StringIO

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sn

# This is what I wish I had.
csv_source1 = StringIO("""\
year,Apples,Bananas,Cherries
1990,1,2,3
1997,1,4,9
1999,1,8,27
""")
df1 = pd.read_csv(csv_source1, index_col=0)
df1.index.names = ['Year']
df1.columns.names = ['fruit']

# This is what I actually have.
csv_source2 = StringIO("""\
fruit,1990,1997,1999
Apples,1,1,1
Bananas,2,4,8
Cherries,3,9,27
""")
# So I transpose it.
df2 = pd.read_csv(csv_source2, index_col=0).T
df2.index.names = ['Year']

sn.set()
ax = plt.subplot(211)
df1.plot(ax=ax)

ax = plt.subplot(212)
df2.plot(ax=ax)

plt.tight_layout()
plt.show()
生成这对图的:

我想画出这些年来每种水果的价格,但我读到的数据是每种水果的一行,每一年的一列。第一个图显示了当我绘制我希望拥有的数据时会发生什么。第二个图显示了在进行转置后绘制数据时发生的情况

df2 = pd.read_csv(csv_source2, index_col=0)
df2.columns = df2.columns.astype(int)
df2 = df2.T

为什么年份没有显示在第二个图的x轴上?数据是均匀分布的,所以它甚至不读取年份数据吗?

当年份数据位于标题行时,它看起来像是作为字符串读取的,然后它就不能用作x轴的数据。要将年份转换为整数,请在进行转置之前转换列

df2 = pd.read_csv(csv_source2, index_col=0)
df2.columns = df2.columns.astype(int)
df2 = df2.T
这是带有更改的完整脚本

from io import StringIO

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sn

# This is what I wish I had.
csv_source1 = StringIO("""\
year,Apples,Bananas,Cherries
1990,1,2,3
1997,1,4,9
1999,1,8,27
""")
df1 = pd.read_csv(csv_source1, index_col=0)
df1.index.names = ['Year']
df1.columns.names = ['fruit']

# This is what I actually have.
csv_source2 = StringIO("""\
fruit,1990,1997,1999
Apples,1,1,1
Bananas,2,4,8
Cherries,3,9,27
""")
# So I convert the years to integers and transpose it.
df2 = pd.read_csv(csv_source2, index_col=0)
df2.columns = df2.columns.astype(int)
df2 = df2.T
df2.index.names = ['Year']

sn.set()
ax = plt.subplot(211)
df1.plot(ax=ax)

ax = plt.subplot(212)
df2.plot(ax=ax)

plt.tight_layout()
plt.show()
固定的绘图使它们都相同