【问题标题】:How to compute correlation between all variables?如何计算所有变量之间的相关性?
【发布时间】:2020-05-20 19:23:34
【问题描述】:

我之前清理了我的数据集,我正在尝试从我的 csv 文件中计算一些变量之间的相关性。 这是我所有的专栏:

Index(['ID', 'age', 'sex', 'city', 'province', 'country', 'latitude',
       'longitude', 'geo_resolution', 'date_onset_symptoms',
       'date_admission_hospital', 'date_confirmation', 'symptoms',
       'lives_in_Wuhan', 'travel_history_dates', 'travel_history_location',
       'reported_market_exposure', 'additional_information',
       'chronic_disease_binary', 'chronic_disease', 'source',
       'sequence_available', 'outcome', 'date_death_or_discharge',
       'notes_for_discussion', 'location', 'admin3', 'admin2', 'admin1',
       'country_new', 'admin_id', 'data_moderator_initials',
       'travel_history_binary'],
      dtype='object')

  • 我通过执行 df.corr 计算了相关性,得到了以下输出:
                        latitude  longitude  chronic_disease_binary  admin_id
latitude                1.000000   0.180020               -0.027188  0.172725
longitude               0.180020   1.000000                0.016198  0.242909
chronic_disease_binary -0.027188   0.016198                1.000000 -0.007604
admin_id                0.172725   0.242909               -0.007604  1.000000

我试图计算性别和纬度之间的相关性,以了解为什么我不能拥有所有列并且出现转换错误:

TypeError: /: 'str' 和 'int' 的操作数类型不受支持

如何计算所有变量之间的相关性?

【问题讨论】:

  • 其中一列是字符串类型。您无法关联字符串和整数类型的特征。

标签: python pandas data-science correlation


【解决方案1】:

我认为有些列由数字字符串 repr 填充。

您可以对所有列使用 to_numeric 将非数字转换为缺失值,然后仅删除 NaNs 列:

df = df.apply(lambda x: pd.to_numeric(x, errors='coerce')).dropna(how='all', axis=1).corr()

或者如果需要在列表中指定列进行处理:

cols = ['age','latitude','longitude']
df = df[cols].apply(lambda x: pd.to_numeric(x, errors='coerce')).corr()

【讨论】:

    猜你喜欢
    • 2019-02-14
    • 2014-04-12
    • 2017-05-02
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    相关资源
    最近更新 更多