为什么Pandas对行数不同的两个CSV计算时输出全表NAN值
问题解决方法
问题根源
NaN是pandas索引对齐规则导致的:仅1行的static DataFrame只有索引0,和24行的dynamic做运算时,仅索引0的行能匹配到static的取值,其余索引无对应值就返回NaN。你推测的行数不一致是完全正确的。
解决方案
你想到的把static的取值存为常量变量的方案完全可行,也是最简洁易读的解决方案。只需在读取static后,将所有字段的取值提取为标量即可,后续计算用这些标量和dynamic的列运算,不会触发索引对齐逻辑,也就不会出现NaN。
修改后的代码参考:
#Step 1 - Reading the input file static = pd.read_csv("Static_Data.csv", sep=';', na_values='(missing)') dynamic = pd.read_csv("Dynamic_data.csv", sep=';', na_values='(missing)') # 提取static的所有静态参数为标量 height = static['Height(m)'].iloc[0] depth = static['Depth(m)'].iloc[0] length = static['Length(m)'].iloc[0] window_wall_ratio = static['Awindow/Awall'].iloc[0] air_change_rate = static['Air Changes/hour (h^-1)'].iloc[0] u_walls = static['Uwalls(W/m2K)'].iloc[0] q_people = static['Qpeople(W)'].iloc[0] solar_gain = static['Window Solar Gain'].iloc[0] #Physical properties calculations A_win = height * (depth + length)*2 * window_wall_ratio #Area of walls A_wall = height * (depth + length)*2 * (1 - window_wall_ratio) * 1.225 #Area of windows t_ext = 20 m_dot = air_change_rate * height * (depth * length) c_p = 1.0021 u_wall = u_walls #Calculation of energy flows inside the house Energy_flows = pd.DataFrame(columns=[]) Energy_flows['Q_exterior'] = u_walls * A_wall * (dynamic['Temp'] - t_ext)/1000 Energy_flows['Q_interior'] = Energy_flows['Q_exterior'] Energy_flows['Q_windows'] = u_walls * A_wall * ( dynamic['Temp'] - t_ext)/1000 Energy_flows['Q_ventil'] = c_p * m_dot * (t_ext - dynamic['Temp'])/3600 Energy_flows['Q_intern'] = q_people * dynamic['Occupation']/1000 Energy_flows['Q_solar'] = solar_gain * height * (depth + length)* window_wall_ratio * dynamic['Rad (W/m^2)']/1000 Energy_flows['Q_envelope'] = Energy_flows['Q_exterior'] + Energy_flows['Q_interior'] + Energy_flows['Q_windows'] Energy_flows['Q_heating/cool'] = Energy_flows['Q_envelope'] + Energy_flows['Q_intern'] + Energy_flows['Q_ventil'] + Energy_flows['Q_solar']
内容的提问来源于stack exchange,提问作者Ilaha
相关产品推荐
相关产品推荐

