Pandas系列循环具有特定的索引级别

问题描述 投票:0回答:1

我有一个带有多个索引的Pandas系列,我试图通过级别“ID”迭代。想法是for循环将递增到下一个“ID”,因此我可以将与该ID相关联的所有值切片以传递给用于将每个ID绘制为不同颜色的函数。

                rest        confidence
ID  ts      
33  21:30:50    150.01001   95.9864
    21:30:52    148.826187  79.530624
    21:30:53    148.957123  54.75795
55  21:30:52    168.325577  37.43358
    21:30:53    172.813446  33.133442
61  21:30:50    107.335625  32.807873

Pandas doc(Pandas MultiIndex)帮助切片并获得循环工作(下图)。使用df.index.levels [0]返回运行for循环所需的索引值,但是,似乎有更好的和告诉它迭代给定索引级别的更快方法。有吗?

for IDn in list(df.index.levels[0]):
    print( df.loc[ (IDn,slice(None)),['confidence','rest'] ].xs(slice(None),level='ID') )

我已经完成了一些问题(Pandas how to loop through a MultiIndex series),看起来groupby和apply函数就是这样。

python pandas indexing series
1个回答
2
投票

您可以使用groupby()并遍历组。首先重新创建数据帧:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

index = pd.MultiIndex.from_product([[33, 55, 61],['21:30:50','21:30:52','21:30:53']], names=['ID','ts'])

df = pd.DataFrame([[150.01001,   95.9864],
                [148.826187,  79.530624],
                [148.957123,  54.75795],
                [np.nan, np.nan],
                [168.325577,  37.43358],
                [172.813446,  33.133442],
                [107.335625,  32.807873],
                [np.nan, np.nan],
                [np.nan, np.nan]],
                columns=['rest', 'confidence'], index=index).dropna()

产量:

                   rest  confidence
ID ts                              
33 21:30:50  150.010010   95.986400
   21:30:52  148.826187   79.530624
   21:30:53  148.957123   54.757950
55 21:30:52  168.325577   37.433580
   21:30:53  172.813446   33.133442
61 21:30:50  107.335625   32.807873

然后使用groupby('ID')

grouped = df.groupby('ID')

fig, ax = plt.subplots()
for name, group in grouped:
    ax.plot(group['rest'], group['confidence'], marker='o', linestyle='', label=name)
ax.legend()

plt.xlabel('rest'); plt.ylabel('confidence')
plt.title('Rest vs Confidence'); plt.grid(True)

plt.show()

生成以下散点图:

enter image description here

UPDATE

要为两个参数与时间(ts)创建两个子图:

df = df.reset_index()

df['ts'] = pd.to_datetime(df['ts'])

grouped = df.groupby('ID')

fig, (ax1, ax2) = plt.subplots(1, 2)
for name, group in grouped:
    ax1.plot(group['ts'], group['rest'], marker='o', linestyle='', label=name)
    ax2.plot(group['ts'], group['confidence'], marker='o', linestyle='', label=name)

ax1.legend()
ax1.set_xlabel('ts'); ax1.set_ylabel('rest')
ax1.set_title('Rest vs ts'); ax1.grid(True)

ax2.legend()
ax2.set_xlabel('ts'); ax2.set_ylabel('confidence')
ax2.set_title('Confidence vs ts'); ax2.grid(True)

plt.show()

这给出了以下内容:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.