【问题标题】:How can I tell if a dataframe is of mixed type?如何判断数据框是否为混合类型?
【发布时间】:2017-10-17 15:50:50
【问题描述】:

我想为数据框的对角线赋值。我能想到的最快方法是使用 numpy 的 np.diag_indices 并对 values 数组进行切片分配。但是,values 数组只是一个视图,并且当数据框是单个 dtype 时可以接受赋值

考虑数据框d1d2

d1 = pd.DataFrame(np.ones((3, 3), dtype=int), columns=['A', 'B', 'C'])
d2 = pd.DataFrame(dict(A=[1, 1, 1], B=[1., 1., 1.], C=[1, 1, 1]))

d1

   A  B  C
0  0  1  1
1  1  0  1
2  1  1  0

d2

   A    B  C
0  1  1.0  1
1  1  1.0  1
2  1  1.0  1

然后让我们获取我们的索引

i, j = np.diag_indices(3)

d1 是单个dtype,因此,这是可行的

d1.values[i, j] = 0
d1

   A  B  C
0  0  1  1
1  1  0  1
2  1  1  0

但不是d2

d2.values[i, j] = 0
d2

   A    B  C
0  1  1.0  1
1  1  1.0  1
2  1  1.0  1

df 是混合dtype 时,我需要编写一个函数并使其失败。我如何测试它是?我是否应该相信如果是这样,通过视图进行的分配将始终有效?

【问题讨论】:

  • 您检查d1.dtypes,它本身就是一个Series,然后检查是否都具有相同的值。
  • 你的意思是d2.dtypes.nunique()>1?

标签: python pandas numpy


【解决方案1】:

您可以使用内部_is_mixed_type 方法

In [3600]: d2._is_mixed_type
Out[3600]: True

In [3601]: d1._is_mixed_type
Out[3601]: False

或者,检查唯一的dtypes

In [3602]: d1.dtypes.nunique()>1
Out[3602]: False

In [3603]: d2.dtypes.nunique()>1
Out[3603]: True

绕道而行,is_mixed_type 检查blocks 是如何合并的。

In [3618]: len(d1.blocks)>1
Out[3618]: False

In [3619]: len(d2.blocks)>1
Out[3619]: True

In [3620]: d1.blocks    # same as d1.as_blocks()
Out[3620]:
{'int32':    A  B  C
 0  0  1  1
 1  1  0  1
 2  1  1  0}

In [3621]: d2.blocks
Out[3621]:
{'float64':      B
 0  1.0
 1  1.0
 2  1.0, 'int64':    A  C
 0  1  1
 1  1  1
 2  1  1}

【讨论】:

  • 我已经在源代码中看到过很多次了 :) 虽然无法给出这个答案 +1
【解决方案2】:
def check_type(df):
  return len(set(df.dtypes)) == 1

 def check_type(df):
   return df.dtypes.nunique() == 1

【讨论】:

  • A set(..) 永远不会等于 1。它可以等于 {1}(虽然不是在这里)。你可能想要len(set(df.dtypes))
  • @WillemVanOnsem 应该是 len
【解决方案3】:

您可以检查DataFrame.dtypes 以检查列的类型。例如:

>>> d1.dtypes
A    int64
B    int64
C    int64
dtype: object
>>> d2.dtypes
A      int64
B    float64
C      int64
dtype: object

鉴于至少有一列,因此您可以通过以下方式进行检查:

np.all(d1.dtypes == d1.dtypes[0])

对于您的数据框:

>>> np.all(d1.dtypes == d1.dtypes[0])
True
>>> np.all(d2.dtypes == d2.dtypes[0])
False

您当然可以先检查是否有至少一列。所以我们可以构造一个函数:

def all_columns_same_type(df):
    dtypes = df.dtypes
    return not dtypes.empty and np.all(dtypes == dtypes[0])

【讨论】:

    猜你喜欢
    • 2017-08-30
    • 2013-08-19
    • 2012-06-07
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    相关资源
    最近更新 更多