【问题标题】:How to change the value of int elements in series如何更改系列中int元素的值
【发布时间】:2018-11-13 22:51:02
【问题描述】:

我只想更改本系列中的int 元素。 我想打印 str 不变的值并打印所有 int 元素的平方值。 为什么它不起作用?

ser3=pd.Series([100,'bulya',300,'asya'], ['tom','bob','cat','foot']) 
print(ser3) 
for i in ser3.iloc[[]]:
    if type(ser3.iloc[i]) == str:
        print (ser3.iloc[[i]])
    else:
        print (ser3.iloc[[i]]**2)

【问题讨论】:

    标签: python pandas conditional-statements series


    【解决方案1】:

    您可以将pd.Series.apply 与自定义函数一起使用。

    ser3 = pd.Series([100,'bulya',300,'asya'], ['tom','bob','cat','foot'])
    
    res = ser3.apply(lambda x: x**2 if isinstance(x, int) else x)
    
    print(res)
    
    tom     10000
    bob     bulya
    cat     90000
    foot     asya
    dtype: object
    

    但是,在我看来,这是对 Pandas 的滥用。我建议您重组数据,以便将数字数据保存在数字系列中。然后,您将能够以矢量化方式执行操作。

    例如,要仅提取数字的平方,您可以使用pd.to_numeric 后跟dropna

    res = pd.to_numeric(ser3, errors='coerce').dropna()**2
    
    print(res)
    
    tom    10000.0
    cat    90000.0
    dtype: float64
    

    【讨论】:

      【解决方案2】:

      您可以通过映射type 并使用int 测试相等性来获得子系列。然后过滤和平方。

      ser3.loc[ser3.map(type) == int] ** 2
      
      tom    10000
      cat    90000
      dtype: object
      

      然后您可以使用update 方法更新系列。

      ser3.update(ser3.loc[ser3.map(type) == int] ** 2)
      ser3
      
      tom     10000
      bob     bulya
      cat     90000
      foot     asya
      dtype: object
      

      【讨论】:

        【解决方案3】:

        to_numericfillna

        (pd.to_numeric(df, errors='coerce')**2).fillna(df)
        
        tom     10000
        bob     bulya
        cat     90000
        foot     asya
        dtype: object
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-10-14
          • 2021-11-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-04-24
          相关资源
          最近更新 更多