【问题标题】:How to identify if an element in a column is integer or a string?如何识别列中的元素是整数还是字符串?
【发布时间】:2019-08-02 00:47:21
【问题描述】:

我正在尝试识别熊猫系列中元素的整数或字符串。该列的dtype是object。

transaction id
654656
546466
654646
844886
C846464
C384448
C468788
C873316

前缀中包含C的元素为字符串,其余为整数。

我尝试使用 if else,但出现错误

for n in data_clean['transaction id']:
    if data_clean['transaction id'].is_integer():
        data_clean['transaction status'] = 1
    elif data_clean['transaction id'].is_str():
        data_clean['transaction status'] = 0

我希望输出是一个新列,如果它是一个整数,则输出为“Ordered”,如果它是一个字符串,则输出为“Cancelled”。

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    使用pandas.Series.str.isnumeric():

    df['transaction status'] = df['transaction id'].str.isnumeric().astype(int)
    print(df)
    

    输出:

      transaction id  transaction status
    0         654656                   1
    1         546466                   1
    2         654646                   1
    3         844886                   1
    4        C846464                   0
    5        C384448                   0
    6        C468788                   0
    7        C873316                   0
    

    【讨论】:

    • 它给出错误“无法将浮点 NaN 转换为整数”。我试过 isnull().any() 但它返回 False。
    【解决方案2】:
    data_clean['transaction status'] = pd.notna(pd.to_numeric(data_clean['transaction id'], errors='coerce')).astype(int)
    

    首先,pd.to_numeric 将列转换为数字格式。因为当交易被取消时,我在行中有字符串,所以这些被作为错误拾取。设置 errors=coerce 将为这些行提供 NaN。

    其次,使用 pd.notna,NaN 设置为 False,数字设置为 True。

    第三,astype(int) 将 True/False 转换为 1/0。

    【讨论】:

      【解决方案3】:

      对于你的 for 循环中的每次迭代,可能是这样的:

      if type(data_clean['transaction id']) == int:
          X = 1
      else:
          X = 0
      

      【讨论】:

        【解决方案4】:

        您可以使用np.where 定义一个条件,根据该条件您可以给出一些选择。如果您的交易有数字 ID,我们将输入Ordered,否则输入Cancelled。我希望只有这两个条件,否则你可以定义一组conditions和对应的choices

        df['transaction status'] = np.where(df['transaction id'].str.isnumeric().astype(int), 'Ordered', 'Cancelled')
        

        输出:

          transaction id transaction status
        0         654656            Ordered
        1         546466            Ordered
        2         654646            Ordered
        3         844886            Ordered
        4        C846464          Cancelled
        5        C384448          Cancelled
        6        C468788          Cancelled
        7        C873316          Cancelled
        

        【讨论】:

        • 请在您的答案中添加一些上下文!你认为读者会明白它的作用吗?
        猜你喜欢
        • 2014-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-10
        相关资源
        最近更新 更多