【问题标题】:Correlation between two cells Python两个单元格Python之间的相关性
【发布时间】:2020-10-06 09:23:56
【问题描述】:
data = {'Brand':  ['Brand A', 'Brand B','Brand C','Brand D'],
        'Likes': [40500, 39400,25020,28900],
         'Sales Contribution': [0.019,0.307,0.21,0.13]
        }
df = pd.DataFrame.from_dict(data)

使用df.corr(),我可以找到变量LikesSales Contribution之间的相关性。 我想找到每个品牌的喜欢和销售贡献之间的相关性。 我该怎么做?

for row in df:
    print(df['Likes'][row].corr(df['Sales Contribution'][row]))

结果

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-52-d54aac6b3ce8> in <module>
      6 df = pd.DataFrame.from_dict(data)
      7 for row in df:
----> 8     print(df['Likes'][row].corr(df['Sales Contribution'][row]))

E:\Anaconda\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    869         key = com.apply_if_callable(key, self)
    870         try:
--> 871             result = self.index.get_value(self, key)
    872 
    873             if not is_scalar(result):

E:\Anaconda\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key)
   4402         k = self._convert_scalar_indexer(k, kind="getitem")
   4403         try:
-> 4404             return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))
   4405         except KeyError as e1:
   4406             if len(self) > 0 and (self.holds_integer() or self.is_boolean()):

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

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: 'Brand'

【问题讨论】:

    标签: python python-3.x dataframe correlation


    【解决方案1】:

    您需要在使用 df.corr() 之前将数据转换为数据框,试试这个

    import pandas as pd
    data = {'Brand':  ['Brand A', 'Brand B','Brand C','Brand D'],
        'Likes': [40500, 39400,25020,28900],
         'Sales Contribution': [0.019,0.307,0.21,0.13]
        }
    df = pd.DataFrame.from_dict(data)
    for index, row in df.iterrows():
        print(df['Likes'][row].corr(df['Sales Contribution'][row]))
    

    【讨论】:

    • 我已经更新了代码,但仍然包含错误。请参考更新后的问题。
    • 用于索引,df.iterrows() 中的行:在上面的代码中,它解决了 keyerror 但 corr 函数将 nan 作为输出,查看文档pandas.pydata.org/pandas-docs/stable/reference/api/…,我不是确定您在相关部分尝试做什么。
    【解决方案2】:

    将熊猫导入为 pd 你的字典 df = pd.DataFrame.from_dict(数据) 对于 df 中的行:

    【讨论】:

    • 我已经更新了代码,但仍然包含错误。请参考更新后的问题。
    猜你喜欢
    • 2022-08-03
    • 2022-08-11
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 2016-05-30
    • 2011-06-14
    • 1970-01-01
    相关资源
    最近更新 更多