Pandas DataFrame对数运算报KeyError问题排查求助
问题根源分析
你遇到的KeyError是因为DataFrame的结构在处理流程中已经发生了本质变化,xvalues不再是可直接访问的列:
- 执行
df_thd_funct.set_index('xvalues', inplace=True)后,xvalues从普通列变成了行索引,此时原DataFrame里已经没有名为xvalues的列了。 - 紧接着的
df_thd_funct = df_thd_funct.T完成转置操作,原来的行索引(即xvalues的数值)变成了转置后DataFrame的列名,原来的列名则转为行索引。
所以无论你用df_thd_funct.xvalues还是df_thd_funct['xvalues'],都找不到对应的列,自然抛出KeyError。
两种解决方法
方法一:调整处理顺序(推荐,逻辑更清晰)
如果业务允许,先计算sensi列,再执行索引设置和转置:
import pandas as pd import numpy as np # 读取原始数据 df_thd_funct = pd.read_csv("A2_THD_Ratio_Stepped_Sweep_Corners_PVT_lab01.txt", delim_whitespace=True, index_col=False) # 先计算sensi列 df_thd_funct['sensi'] = 20 * np.log(df_thd_funct['xvalues'] / 1.44) # 再执行索引设置与转置 df_thd_funct.set_index('xvalues', inplace=True) df_thd_funct = df_thd_funct.T check_for_nan = df_thd_funct.isnull().values.any() print(check_for_nan) df_thd_funct.head()
方法二:基于转置后的结构计算
如果必须保持现有处理流程,需要从转置后的列名(即原xvalues的数值)取值计算,将sensi作为新行添加:
import pandas as pd import numpy as np # 原处理流程 df_thd_funct = pd.read_csv("A2_THD_Ratio_Stepped_Sweep_Corners_PVT_lab01.txt", delim_whitespace=True, index_col=False) df_thd_funct.set_index('xvalues', inplace=True) check_for_nan = df_thd_funct.isnull().values.any() df_thd_funct = df_thd_funct.T print(check_for_nan) # 基于列名(原xvalues)计算sensi,添加为新行 sensi_values = 20 * np.log([col / 1.44 for col in df_thd_funct.columns]) df_thd_funct.loc['sensi'] = sensi_values df_thd_funct.head()
注意:
np.log计算的是自然对数,若你需要的是常用对数(以10为底),请替换为np.log10。
内容的提问来源于stack exchange,提问作者Confused
相关产品推荐
相关产品推荐

