【问题标题】:Pandas dataframe count Strings and Postive numbers in one column一列中的熊猫数据框计数字符串和正数
【发布时间】:2023-01-05 22:31:03
【问题描述】:

我有一个数据框,它有一列“A1”,其中包含多个“Hello”字符串,正整数和负整数。我想计算“Hello”字符串,所有数字 >= 0 和所有数字 < 0,以便最后得到三个和。

index A1
0 1
1 Hello
2 -8
3 Hello

所以输出应该是 posNums 1、negNums 1 和 helloCount 2

posNums = df.where(df['A1'] >= 0).sum()

这显然不起作用,因为无法将字符串与 int 进行比较。但是,当我计算整数时,如何在此处添加一些跳过 str 的条件,反之亦然?

【问题讨论】:

  • 提供示例输入和预期输出
  • 请阐明您的具体问题或提供更多详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: python pandas dataframe


【解决方案1】:

一种方法是使用 pd.to_numeric:

import pandas as pd

df = pd.DataFrame({"A1": ["Hello", 1, -1, "Hello", "Hello", -2, 2, -3]})

agg_funcs = {
    "negative": lambda x: x.lt(0).sum(),
    "positive": lambda x: x.ge(0).sum(),
    "nans":     lambda x: x.isna().sum()
}

out = pd.to_numeric(df["A1"], errors="coerce").agg(agg_funcs)

出去:

negative    3
positive    2
nans        3
Name: A1, dtype: int64

【讨论】:

    【解决方案2】:

    您正在寻找这样的东西吗?

    df = pd.DataFrame({'A1': ['hello', 1, 2, 3, 4, 5, -1, -2, -3, -4, -5, 'world']})
    count_pos = df[df['A1'].apply(lambda x: isinstance(x, int) and x > 0)].count()
    count_neg = df[df['A1'].apply(lambda x: isinstance(x, int) and x < 0)].count()
    count_str = df[df['A1'].apply(lambda x: isinstance(x, str))].count()
    
    Will output:
    A1    5
    dtype: int64
    A1    5
    dtype: int64
    A1    2
    dtype: int64
    

    【讨论】:

      猜你喜欢
      • 2018-02-04
      • 1970-01-01
      • 2015-05-18
      • 2018-04-26
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 2016-07-30
      相关资源
      最近更新 更多