【问题标题】:Concatenation error (Wrong number of items passed x, placement implies 1)连接错误(通过 x 的项目数错误,位置意味着 1)
【发布时间】:2019-08-22 16:14:15
【问题描述】:

我有一个这样的数据框:

a            b
thing1      1.00
thing2      2.71 

a 列是字符串,b 列是 float64,我正在尝试将帧转换为如果 b 列为 1,则返回 1,如果 b 列中的值大于 1,则返回 2.71/6,2.71R24, 1

a         b       c
thing1    1       1
thing2    2.71    2.71/6,2.71R24,1

我试过这样的功能

def convert (row):
    if row['b'] == 1.00:
        return '1' 
    else:
        return df['b'].astype(str)+'/6,'+df['b'].astype(str)+'R24,1'
df['c']  = df.apply(lambda row: convert (row), axis=1)

我收到以下错误:

ValueError: Wrong number of items passed 15, placement implies 1

我似乎无法绕过这个错误?

【问题讨论】:

    标签: pandas error-handling type-conversion concatenation


    【解决方案1】:

    尝试使用np.where

    df['c']=np.where(df.b==1,1,df.b.astype(str)+'/6,'+df.b.astype(str)+'R24,1')
    df
    Out[504]: 
            a     b                 c
    0  thing1  1.00                 1
    1  thing2  2.71  2.71/6,2.71R24,1
    

    【讨论】:

    • 差不多,只考虑“值大于1”
    猜你喜欢
    • 2022-07-19
    • 2018-11-03
    • 2020-10-30
    • 2022-01-13
    • 2019-05-17
    • 2023-03-24
    • 2019-03-19
    • 2020-09-17
    • 2021-11-26
    相关资源
    最近更新 更多