【问题标题】:How to add series of dictionary with unknown number of keys如何添加具有未知键数的字典系列
【发布时间】:2019-02-12 16:26:27
【问题描述】:

我创建了以下字典 test,由 Series 对象组成:

test = {
    'A': pd.Series([True, False, True]),
    'B' : pd.Series([True,False,False])
}

我想执行test['A'] & test['B']。我的问题是我想对字典中任何可能数量的键进行按位加法。 (即它可以是'A''A' and 'B''A' and 'B' and 'C' 等)。在任何情况下,每个键的值都具有相同的长度,并且所有的Series 都是布尔值。

【问题讨论】:

  • 为什么不使用 DataFrame?
  • 问题:您是要按位执行 KEYS 还是实际执行 VALUES?当我按位读取 KEYS 时,我的字面意思是:'A' | 'B'

标签: python pandas dictionary series bitwise-and


【解决方案1】:

使用DataFrame 而不是Series 对象的字典有很多优点。从后者转换为前者是微不足道的:

>>> df = pd.DataFrame(test)
>>> df
       A      B
0   True   True
1  False  False
2   True  False

虽然DataFrame 构造函数在解析输入数据方面非常聪明,但您可以使用from_dict classmethod 明确告诉它您正在从字典中初始化:

>>> df = pd.DataFrame.from_dict(test)

现在您可以使用all 方法沿您想要的任何轴应用&

>>> df.all(axis=1) # going across
0     True
1    False
2    False
dtype: bool

| 使用 any 也是如此:

>>> df.any(axis=1)
0     True
1    False
2     True
dtype: bool

【讨论】:

  • 确实通过转换为数据框,它是直截了当的。非常感谢!我知道 Series 不会以简单的方式提供这种操作。
  • @NSK。他们会这样做,但不是针对任意数量的。
【解决方案2】:

有一个简单的单行解决方案可以解决您的问题(如果您想对列进行累积 and 操作,例如 A and BA and B and CA and B and C and D 等):

import pandas as pd

test = {
    "A": pd.Series([True, True, True]),
    "B": pd.Series([True, False, False]),
    "C": pd.Series([False, True, False]),
    "D": pd.Series([True, False, False]),
}

df = pd.DataFrame.from_dict(test)

# Here is da man    
print(df.cummin(axis="columns"))

使用cummin,如果有任何值是False,后面的都是False,也是最小值。

原始数据框:

      A      B      C      D
0  True   True  False   True
1  True  False   True  False
2  True  False  False  False

累计and

      A      B      C      D
0  True   True  False  False
1  True  False  False  False
2  True  False  False  False

第一列是A,第二列是A and B,第三列是A and B and C,最后是A and B and C and D

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    相关资源
    最近更新 更多