gpt4 book ai didi

python - 如果pandas中的值是 float (不是字符串),则将列除以其他列?

转载 作者:行者123 更新时间:2023-12-01 08:56:16 26 4
gpt4 key购买 nike

我有以下数据框并尝试应用以下命令。但是,由于每列都包含某些行的字符串,因此出现错误。谁能告诉我如何修改此脚本以在值为字符串时跳过计算?

df["diff"] = (df["value"] / df["value_B"] - 1) * 100  

数据框

                                                        value    value_B
GeneralEUI[kWh/m2]EUI[kWh/m2]EUI[kWh/m2] 217.3 243.3
GeneralTotal Unmer Hour[h]Total Unmer Hour[h]To... 536 536
GeneralTotal Area[m2]Total Area[m2]Total Area[m2] 51513 51513
GeneralLocationLocationLocation Hong Kong Hong Kong
GeneralProgramProgramProgram Office Office
EnvelopeTotal Window to Wall Ratio [%]Total Win... 52.23 52.23
EnvelopeGlassSHGC value 0.24 0.24
EnvelopeGlassU-value[W/m2-K] 1.74 1.74
EnvelopeGlassOFFICE WINDOWSHGC value 0.22 0.22
EnvelopeGlassOFFICE WINDOWU-value[W/m2-K] 1.63 1.63
EnvelopeGlassPODIUM WINDOWSHGC value 0.7 0.7
EnvelopeGlassPODIUM WINDOWU-value[W/m2-K] 5.48 5.48
EnvelopeOpaqueSHGC value 0.24 0.24
EnvelopeOpaqueU-value[W/m2-K] 1.74 1.74
EnvelopeOpaqueOFFICE WINDOWSHGC value 0.22 0.22

最佳答案

您可以通过 to_numeric 将字符串转换为缺失值带参数errors='coerce':

a = pd.to_numeric(df["value"], errors='coerce')
b = pd.to_numeric(df["value_B"], errors='coerce')

df["diff"] = (a / b - 1) * 100
<小时/>
print (df)
value value_B \
GeneralEUI[kWh/m2]EUI[kWh/m2]EUI[kWh/m2] 217.3 243.3
GeneralTotal Unmer Hour[h]Total Unmer Hour[h]To... 536 536
GeneralTotal Area[m2]Total Area[m2]Total Area[m2] 51513 51513
GeneralLocationLocationLocation Hong Kong Hong Kong
GeneralProgramProgramProgram Office Office
EnvelopeTotal Window to Wall Ratio [%]Total Win... 52.23 52.23
EnvelopeGlassSHGC value 0.24 0.24
EnvelopeGlassU-value[W/m2-K] 1.74 1.74
EnvelopeGlassOFFICE WINDOWSHGC value 0.22 0.22
EnvelopeGlassOFFICE WINDOWU-value[W/m2-K] 1.63 1.63
EnvelopeGlassPODIUM WINDOWSHGC value 0.7 0.7
EnvelopeGlassPODIUM WINDOWU-value[W/m2-K] 5.48 5.48
EnvelopeOpaqueSHGC value 0.24 0.24
EnvelopeOpaqueU-value[W/m2-K] 1.74 1.74
EnvelopeOpaqueOFFICE WINDOWSHGC value 0.22 0.22

diff
GeneralEUI[kWh/m2]EUI[kWh/m2]EUI[kWh/m2] -10.686395
GeneralTotal Unmer Hour[h]Total Unmer Hour[h]To... 0.000000
GeneralTotal Area[m2]Total Area[m2]Total Area[m2] 0.000000
GeneralLocationLocationLocation NaN
GeneralProgramProgramProgram NaN
EnvelopeTotal Window to Wall Ratio [%]Total Win... 0.000000
EnvelopeGlassSHGC value 0.000000
EnvelopeGlassU-value[W/m2-K] 0.000000
EnvelopeGlassOFFICE WINDOWSHGC value 0.000000
EnvelopeGlassOFFICE WINDOWU-value[W/m2-K] 0.000000
EnvelopeGlassPODIUM WINDOWSHGC value 0.000000
EnvelopeGlassPODIUM WINDOWU-value[W/m2-K] 0.000000
EnvelopeOpaqueSHGC value 0.000000
EnvelopeOpaqueU-value[W/m2-K] 0.000000
EnvelopeOpaqueOFFICE WINDOWSHGC value 0.000000

关于python - 如果pandas中的值是 float (不是字符串),则将列除以其他列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52754657/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com