有一些csv格式的实验数据表。我像这样导入它:
>>> import pandas as pd
>>> df = pd.read_csv('data.csv', sep=',')
>>> df
'Set' 'Rx' 'Traffic' 'Modulation'
0 -67.0 -64.35 15.00 '64-QAM 2/3'
1 -68.0 -65.35 15.00 '16-QAM 3/4'
2 -69.0 -66.85 14.78 '64-QAM 2/3'
3 -70.0 -67.60 15.42 '64-QAM 2/3'
4 -71.0 -68.85 15.04 '64-QAM 2/3'
5 -72.0 -70.35 15.04 '16-QAM 3/4'
6 -73.0 -70.85 15.04 '16-QAM 3/4'
7 -74.0 -71.35 15.28 '16-QAM 3/4'
8 -75.0 -72.60 12.35 '64-QAM 2/3'
9 -76.0 -73.10 11.38 '16-QAM 3/4'
10 -77.0 -74.60 11.64 '16-QAM 3/4'
11 -78.0 -75.60 7.76 '16-QAM 1/2'
12 -79.0 -76.85 7.76 '16-QAM 1/2'
13 -80.0 -77.85 7.52 '16-QAM 1/2'
14 -81.0 -79.35 5.85 'QPSK 3/4'
现在我想绘制一个使用“设置”列作为 X 值的图表。在这张图上,我想看到两条(!)曲线:
- Y1:'Rx'
- Y2:“交通”
matplotlib.pyplot如何做到这一点?我找到了一个指南(Pandas),第一步是从表中选择一列,如下所示:
df = pd.read_csv('apple.csv', index_col='Date', parse_dates=True)
new_sample_df = df.loc['2012-Feb':'2017-Feb', ['Close']]
但是我的第一个数据框索引是数字的,我无法选择我感兴趣的列:
new_sample_df = df.iloc[0:14, ['Rx']]
TypeError: cannot perform reduce with flexible type
但即使我能以某种方式做到这一点,我如何将每个 X 点的两个(!) Y 值传递给绘图函数?尝试了两个建议的选项。它不起作用:-(为了消除歧义,我给出了 CSV 文件本身:
'Set,Rx','Traffic','Modulation'
-67.00, -64.35, 15.00, '64-QAM 2/3'
-68.00, -65.35, 15.00, '16-QAM 3/4'
-69.00, -66.85, 14.78, '64-QAM 2/3'
-70.00, -67.60, 15.42, '64-QAM 2/3'
-71.00, -68.85, 15.04, '64-QAM 2/3'
-72.00, -70.35, 15.04, '16-QAM 3/4'
-73.00, -70.85, 15.04, '16-QAM 3/4'
-74.00, -71.35, 15.28, '16-QAM 3/4'
-75.00, -72.60, 12.35, '64-QAM 2/3'
-76.00, -73.10, 11.38, '16-QAM 3/4'
-77.00, -74.60, 11.64, '16-QAM 3/4'
-78.00, -75.60, 7.76, '16-QAM 1/2'
-79.00, -76.85, 7.76, '16-QAM 1/2'
-80.00, -77.85, 7.52, '16-QAM 1/2'
-81.00, -79.35, 5.85, 'QPSK 3/4'
以及我正在尝试执行的程序的文本,注释掉了两个选项:
#!/usr/bin/env python
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(r'data.csv', quotechar="'")
#1 df.set_index('Set')[['Rx','Traffic']].plot(legend=True, grid=True)
#2 df.set_index("'Set'")[["'Rx'","'Traffic'"]].plot(legend=True, grid=True)
如果取消注释 #1,将显示以下消息:
KeyError: 'Set'
如果您取消注释 #2,则消息会相应更改:
KeyError: "'Set'"
也许重点是我是第三条蟒蛇,而例子是第二条?
要正确读取 CSV,其中值和列名用引号括起来,您应该使用参数
quotechar=...:之后,您可以构建如下图:
CSV 文件示例: