【问题标题】:Dict comprehension failing - Python 3.6.x字典理解失败 - Python 3.6.x
【发布时间】:2020-11-10 12:40:11
【问题描述】:

我正在尝试编写一个dict 理解,它创建一个dict,其中k,v 对是column_title, # of null values in that column,我的pandas df

我有以下几点: df1_null_dict = {c:df1.c.isnull().sum() for c in df1}

下面是 this example 如何在 Python 中构建字典推导式。

但是,我得到:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-a4c7d72985f6> in <module>
----> 1 df1_null_dict = {c:df1.c.isnull().sum() for c in df1}
      2 df2_null_dict = {c:df2.c.isnull().sum() for c in df2}

<ipython-input-5-a4c7d72985f6> in <dictcomp>(.0)
----> 1 df1_null_dict = {c:df1.c.isnull().sum() for c in df1}
      2 df2_null_dict = {c:df2.c.isnull().sum() for c in df2}

c:\python367-64\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
   5137             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   5138                 return self[name]
-> 5139             return object.__getattribute__(self, name)
   5140 
   5141     def __setattr__(self, name: str, value) -> None:

AttributeError: 'DataFrame' object has no attribute 'c'

如何使用 dict 理解来实现我想要的结果?

【问题讨论】:

    标签: python python-3.x pandas dataframe dictionary


    【解决方案1】:

    使用[] 选择的替代方法与变量一起工作:

    df1 = pd.DataFrame({
             'C':[np.nan,8,9,4,np.nan,np.nan],
             'D':[1,3,5,np.nan,1,0],
             'E':[np.nan,3,6,9,2,np.nan],
    
    })
    
    df1_null_dict = {c:df1[c].isnull().sum() for c in df1}
    print (df1_null_dict)
    {'C': 3, 'D': 1, 'E': 2}
    

    另一种方法是创建 Series 并转换为字典:

    df1_null_dict = df1.isnull().sum().to_dict()
    print (df1_null_dict)
    {'C': 3, 'D': 1, 'E': 2}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 2019-02-03
      • 2013-01-08
      • 1970-01-01
      • 2022-11-22
      • 2021-07-09
      相关资源
      最近更新 更多