python - Pandas 中的行满足某些条件,将 dos 条件的值分配给一个单元格

标签 python pandas dataframe conditional-statements data-science

我有一个包含一些值的数据框。

假设dos是一些stores的值,并且doesstores可以满足一些条件并赋予它们多个“状态”,但其他stores只能满足一个条件并且只能被分配一个“状态”。

例如:

df = DataFrame({'one':[1,2,3,4],
                'two';[5,6,7,8],
                'three':[9,10,11,12]}

这些是我的条件:

df.loc[(df.one >= 1) & (df.two <= 7),'State'] = 1
df.loc[(df.one == 1) & (df.two <= 11),'State'] = 2

三行满足第一个条件,但只有一行满足第二个条件。

满足两个条件的行应在“State”列中包含状态 1 和 2。

明显的问题是,当第一个条件被分配时,DataFrame 看起来像这样:

    one two three   State
0   1   5   9        1.0
1   2   6   10       1.0
2   3   7   11       1.0
3   4   8   12       NaN

当第二个条件被分配时,数据框看起来像这样:

    one two three   State
0   1   5   9        2.0
1   2   6   10       1.0
2   3   7   11       1.0
3   4   8   12       NaN

我想要这样的东西:

    one two three   State
0   1   5   9        [1.0,2.0]
1   2   6   10       1.0
2   3   7   11       1.0
3   4   8   12       NaN

这里我使用了一个列表,但这就是想法。

然后,如果我在单元格中进行存储,我如何调用它们,以及如何使用“状态”列中具有多个值的单元格来处理依赖于该单元格的其他条件列?

我很欣赏

最佳答案

这是一个棘手的问题,我不建议您在一列中混合数据类型,因为您显示第一个单元格是列表类型,1和2是int类型,然后最后一个是NaN(被视为 float ),在这种情况下为什么不将它们全部列出

s1=(df.one >= 1) & (df.two <= 7)
s2=(df.one == 1) & (df.two <= 11)
l=[[ z for z in [x,y] if z != 0]for x , y in zip(s1*1,s2*2)]
df['State']=l
df
Out[21]: 
   one  two  three   State
0    1    5      9  [1, 2]
1    2    6     10     [1]
2    3    7     11     [1]
3    4    8     12      []

关于python - Pandas 中的行满足某些条件,将 dos 条件的值分配给一个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54469439/

相关文章:

python - 如何根据标准过滤、总结和 reshape 数据框

python - 损坏的 pip 安装仅适用于 sudo

python - 如何删除数组中的部分文本?

python - 使用正则表达式提取不同格式的日期并对它们进行排序 - pandas

python - 将未填充的 m/d/y 格式的日期转换为 python pandas 中的日期时间

python - 根据另一个数据框选择值

python - lambda 函数的内存地址

python - 尝试安装 py -m pip install google-assistant-sdk 时如何修复错误 “ERROR: Command errored out with exit status 1: python.” [示例]

regex - 如何使用某些功能将列拆分为多列?

r - 将预测的时间序列与 R 中的原始序列重叠