python - 如何在熊猫上将唯一的偶数列标题称为x轴,而奇数列用作y轴?
问题描述
我第三次尝试寻找可能的编码解决方案。作为我的编码工作的参考。我附上了我以前的问题。
我发布的第一个问题:如何使所有行数据删除相似数据并乘以浮点数 我发布的第二个问题:如何仅选择偶数标题的特定列?
现在,我想在我的数据上绘制图表。我在这里尝试:
import matplotlib.pylab as plt
fig,axes = plt.subplots(nrows =1,ncols =2,figsize =(15,5))
fig.subplots_adjust(hspace= 0.8)
df2.plot(ax = axes[0])
axes[0].set_title('xxx')
axes[0].set_xlabel('f',fontsize=12,color = 'r')
其输出与我预测的一样,与一般产生的数据一样混乱。如何仅在 x 轴 [偶数列] 和 y 轴 [奇数列] 上设置?在我的图表中。我应该如何在数据框中调用?提前谢谢你。
更新(28/8/2021):
import matplotlib.pylab as plt
fig,axes = plt.subplots(nrows =1,ncols =2,figsize =(15,5))
fig.subplots_adjust(hspace= 0.8)
#df2 =df2.astype(float)
#even_cols = df2.columns[::2]
#odd_cols = df2.columns[1::2]
#df2.plot(ax = axes[0])
#df2[even_columns].plot(ax = axes[0])
#df2[odd_columns].plot(ax = axes[0])
axes[0].set_title('US')
axes[0].set_xlabel('f',fontsize=12,color = 'r')
#axes[0].set_xticklabels('f', rotation=90)
axes[0].set_xlim([0,18])
#axes[0].set_ylim([0,-100])
#ax.legend()
df2.plot(ax = axes[0],legend=False)
#plt.show()
在这里 ,我很抱歉回复晚了,并尝试为我的问题提供建议的答案。得到(-1),这是我应得的迟到反应。无论如何,我拥有的图表并没有显示我想要的图表。
前一个很可能显示了实际图表。在这里 ,如果我的问题让你们感到困惑,我很抱歉。
更新数据 2021 年 8 月 30 日: 这是数据
---更新(2021 年 8 月 31 日)----
fig, ax = plt.subplots()
ax.grid()
for i in range(int(len(df.keys())/2)):
ax.plot(df[f'{df.keys()[i*2]}'], df[f'{df.keys()[i*2+1]}'])
之后我添加了建议。错误显示:
\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2645 try:
-> 2646 return self._engine.get_loc(key)
2647 except KeyError:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()
KeyError: '0'
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
<ipython-input-1-fe714e6030fb> in <module>
19 ax.grid()
20 for i in range(int(len(df.keys())/2)):
---> 21 ax.plot(df[f'{df.keys()[i*2]}'], df[f'{df.keys()[i*2+1]}'])
~\anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
2798 if self.columns.nlevels > 1:
2799 return self._getitem_multilevel(key)
-> 2800 indexer = self.columns.get_loc(key)
2801 if is_integer(indexer):
2802 indexer = [indexer]
~\anaconda3\lib\site-packages\pandas\core\indexes\range.py in get_loc(self, key, method, tolerance)
351 except ValueError:
352 raise KeyError(key)
--> 353 return super().get_loc(key, method=method, tolerance=tolerance)
354
355 @Appender(_index_shared_docs["get_indexer"])
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2646 return self._engine.get_loc(key)
2647 except KeyError:
-> 2648 return self._engine.get_loc(self._maybe_cast_indexer(key))
2649 indexer = self.get_indexer([key], method=method, tolerance=tolerance)
2650 if indexer.ndim > 1 or indexer.size > 1:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()
KeyError: '0'
keyerror 状态是0
什么?然后我尝试调整它。但是,它一直指向0
. 我没有说明第 0 列?
解决方案
这是使用熊猫绘图:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
plt.close()
df = pd.DataFrame()
n = 10
for i in range(4):
df[f'col{i}'] = np.arange(n*i, n*(i+1))
fig,axes = plt.subplots(nrows =1,ncols =2,figsize =(15,5))
axes = axes.ravel()
fig.subplots_adjust(hspace= 0.8)
for i in range(int(len(df.keys())/2)):
df.plot(ax=axes[i], x=f'col{i*2}', y=f'col{i*2+1}')
df
看起来像这样:
col0 col1 col2 col3
0 0 10 20 30
1 1 11 21 31
2 2 12 22 32
3 3 13 23 33
4 4 14 24 34
5 5 15 25 35
6 6 16 26 36
7 7 17 27 37
8 8 18 28 38
9 9 19 29 39
使用此输出:
我不建议这样做。原因是这样的MatplotlibDeprecationWarning
:
The is_first_col function was deprecated in Matplotlib 3.4 and will be removed two minor releases later. Use ax.get_subplotspec().is_first_col() instead.
我建议使用普通的标准 matplotlib 绘图。
代替:
df.plot(ax=axes[i], x=f'col{i*2}', y=f'col{i*2+1}')
从上面的代码:
axes[i].plot(df[f'{df.keys()[i*2]}'], df[f'{df.keys()[i*2+1]}'])
输出相同,但没有警告。随意询问是否有不清楚的地方。
- -编辑 - -
尝试这个。这肯定会奏效:
url = r"https://raw.githubusercontent.com/ZebraKatz/ZebraKatz/ed46b807b1e08b63f56d0cedb8e299e09550d927/us_test_drop.csv"
df = pd.read_csv(url)
df = df.drop(columns=[f'{df.keys()[0]}']) # I assume 0 1 2 3 4 5 and so on are your index, not part of actual data
fig, ax = plt.subplots()
ax.grid()
for i in range(int(len(df.keys())/2)):
ax.plot(df[f'{df.keys()[i*2]}'], df[f'{df.keys()[i*2+1]}'])
输出是:
我意识到你在这里和那里有一些随机点,如果我用标记绘制它,情节看起来像这样:
在这一点上,我不确定这是否真的是您想要实现的输出。您的初始代码与此无关,此外,您在问题中添加的预期输出看起来不像这样。但是,这就是您的数据的样子。如果这不是您想要达到的目标,那么您可能需要再次查看您的数据。
推荐阅读
- python - 为什么我的 GAN 只产生灰色图像而没有任何进展?
- typescript - 打字稿ORM设置默认实体值不起作用
- filter - RankX 在组的子集中
- c++ - 使用 Aws::LexRuntimeV2::LexRuntimeV2Client 的问题 - QT/C++ 中的 RecognizeText
- ansible - jinja2模板中相等测试的sameas条件
- c64 - Commodore C64 如何检测 PAL 或 NTSC
- python - Pytest - 将信息传递给夹具
- javascript - 将 Material-UI Drawer 组件定位在 Appbar 下
- javascript - 错误堆栈的输出不包含所有信息
- android - RxJava 中相互依赖的多个 Retrofit 请求