Python 以2级多索引为轴的熊猫数据帧散点图

Python 以2级多索引为轴的熊猫数据帧散点图,python,pandas,matplotlib,plot,Python,Pandas,Matplotlib,Plot,我有一个带有2级多索引的数据帧df。我想要一个散点图,x轴上有0级,y轴上有1级,所有满足条件的组合都有散点,比如在特定列中有一个非零值'col' import matplotlib.pyplot as plt from itertools import product import numpy as np lengths = [3, 2] df_index = pd.MultiIndex.from_product([list(product([-1,1], repeat=li)) for l

我有一个带有2级多索引的数据帧
df
。我想要一个散点图,x轴上有0级,y轴上有1级,所有满足条件的组合都有散点,比如在特定列中有一个非零值
'col'

import matplotlib.pyplot as plt
from itertools import product
import numpy as np

lengths = [3, 2]
df_index = pd.MultiIndex.from_product([list(product([-1,1], repeat=li)) for li in lengths], names=['level1', 'level2'])

df_cols = ['cols']
df = pd.DataFrame([[0.] * len(df_cols)] * len(df_index), index=df_index, columns=df_cols)
df['cols'] = np.random.randint(0, 2, size = len(df))
df
生成以下形式的数据帧

                       cols
level1       level2        
(-1, -1, -1) (-1, -1)     0
             (-1, 1)      0
             (1, -1)      0
             (1, 1)       0
(-1, -1, 1)  (-1, -1)     1
             (-1, 1)      0
             (1, -1)      1
             (1, 1)       1
(-1, 1, -1)  (-1, -1)     0
             (-1, 1)      0
             (1, -1)      0
             (1, 1)       0
(-1, 1, 1)   (-1, -1)     0
             (-1, 1)      0
             (1, -1)      1
             (1, 1)       0
(1, -1, -1)  (-1, -1)     0
             (-1, 1)      0
             (1, -1)      1
             (1, 1)       1
(1, -1, 1)   (-1, -1)     0
             (-1, 1)      1
             (1, -1)      1
             (1, 1)       0


现在,我想要一个散点图,其中level1索引在x轴上,level2索引在y轴上,这样对于每一个(x,y)cols(x,y)!=0有一个点。

让我们首先创建一个具有两级多索引的示例数据帧:

import pandas as pd
import numpy as np
iterables = [[1, 2, 3, 4], [0,1, 2, 3, 4,5]]
my_multiindex=pd.MultiIndex.from_product(iterables, names=['first', 'second'])
series1 = pd.Series(np.random.randn(24), index=my_multiindex)
series2 = pd.Series(np.random.randn(24), index=my_multiindex)
df=pd.DataFrame({'col1':series1,'col2':series2})
现在,让我们获得满足给定条件的索引值:

index_values=df[df.col1<0].index.values
然后我们绘制:

from matplotlib import pyplot as plt
plt.scatter(xs,ys)
如果希望散射点的大小反映实际值,可以使用:

column_values=abs(df[df.col1<0].col1.values)
plt.scatter(xs,ys,s=column_values*10)

制作一个我们可以运行的自包含示例,以实际数据的形式构造数据(只是更小)。感谢您的回答!对不起,我只是举例说明我的问题。你的答案有效,但在我的情况下,我不能直接使用索引作为坐标。我使用了
多索引。get_indexer
试图获取索引并使用这些索引,但不幸的是,我仍在努力。我刚刚编辑了我的答案以解决您的更改。如果答案能解决你的问题,请接受。
column_values=abs(df[df.col1<0].col1.values)
plt.scatter(xs,ys,s=column_values*10)
plt.figure(figsize=(10,10))
plt.scatter([str(a) for a in xs],[str(a) for a in ys])