【问题标题】:Pandas scatter_matrix - plot categorical variablesPandas scatter_matrix - 绘制分类变量
【发布时间】:2015-03-18 00:52:50
【问题描述】:

我正在查看来自 Kaggle 比赛的著名泰坦尼克号数据集:http://www.kaggle.com/c/titanic-gettingStarted/data

我已使用以下方法加载和处理数据:

# import required libraries
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

# load the data from the file
df = pd.read_csv('./data/train.csv')

# import the scatter_matrix functionality
from pandas.tools.plotting import scatter_matrix

# define colors list, to be used to plot survived either red (=0) or green (=1)
colors=['red','green']

# make a scatter plot
scatter_matrix(df,figsize=[20,20],marker='x',c=df.Survived.apply(lambda x:colors[x]))

df.info()

如何将 Sex 和 Embarked 等分类列添加到情节中?

【问题讨论】:

  • 散点图不是分类变量的好选择,因此将这些变量“添加”到此散点矩阵中没有任何意义。您可以绘制涉及这些变量的一组不同的图(例如,按类别分组的每个数值变量的箱线图)。
  • BrenBarn - 谢谢......我不完全同意你的看法......当因素有限时(如性别:男性,女性,未知)。我发现将这些像 1,2 和 3 这样的整数接近并绘制在散点图中非常有见地。如果我没有记错的话,R 在绘制散点矩阵时会像这样在数据框中处理它的因素。希望可以对熊猫做同样的事情。
  • 我想你会想看看 seaborn 的 facetgrids 和 pairgrids 来处理这种类型的情节:web.stanford.edu/~mwaskom/software/seaborn/examples/…
  • 请注意,对于pandas 版本>0.19,from pandas.tools.plotting import scatter_matrix 应替换为from pandas.plotting import scatter_matrix(cf reference answer)

标签: python pandas matplotlib kaggle


【解决方案1】:

这是我的解决方案:

# convert string column to category
df.Sex = df.Sex.astype('category')
# create additional column for its codes
df['Sex_code'] = df_clean.Sex.cat.codes

【讨论】:

    【解决方案2】:

    在谷歌搜索并记住类似 .map() 函数后,我通过以下方式对其进行了修复:

    colors=['red','green'] # color codes for survived : 0=red or 1=green
    
    # create mapping Series for gender so it can be plotted
    gender = Series([0,1],index=['male','female'])    
    df['gender']=df.Sex.map(gender)
    
    # create mapping Series for Embarked so it can be plotted
    embarked = Series([0,1,2,3],index=df.Embarked.unique())
    df['embarked']=df.Embarked.map(embarked)
    
    # add survived also back to the df
    df['survived']=target
    

    现在我可以再次绘制它...然后删除添加的列。

    感谢大家的回复.....

    【讨论】:

      【解决方案3】:

      您需要将分类变量转换为数字来绘制它们。

      示例(假设“Sex”列包含性别数据,“M”代表男性,“F”代表女性)

      df['Sex_int'] = np.nan
      df.loc[df['Sex'] == 'M', 'Sex_int'] = 0
      df.loc[df['Sex'] == 'F', 'Sex_int'] = 1
      

      现在所有女性都用 0 表示,男性用 1 表示。未知性别(如果有的话)将被忽略。

      您的其余代码应该可以很好地处理更新后的数据帧。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-08
        • 2014-05-21
        • 1970-01-01
        • 2023-03-31
        • 2019-08-09
        • 2019-04-14
        • 1970-01-01
        • 2016-08-01
        相关资源
        最近更新 更多