我在python脚本中使用了熊猫。 python升级后,我的脚本抛出以下错误:
/XXXX/anaconda2/lib/python2.7/site-packages/pandas/io/formats/format.py:1586: FutureWarning:
Passing list-likes to .loc or [] with any missing label will raise
KeyError in the future, you can use .reindex() as an alternative.
我没有看到任何回溯。我如何找出脚本中的哪一行触发了此错误?可能的答案可能也适用于其他警告。
不幸的是,由于某些原因该问题被否决,而不是帮助解决方案。进行一些挖掘后,我发现错误来自代码段:
newDF = {} #pd.DataFrame()
newDF["Time (ns)"] = df["Time"] / ns
newDF["Current (kA)"] = df['Currnt'] / 1000.0
newDF["Power-a"] = df['WSumktot'] * erg_per_sec_to_watt
newDF["Total"] = np.array(df['WSumtot']) * erg_per_sec_to_watt
newDF =pd.DataFrame(newDF)
header = ["Time (ns)" , "Current (kA)", "Power_a", "Total"]
print "before error. The following line triggers the error"
newDF.to_csv("current_data.csv", columns=header, sep=b'\t', float_format='%.5e', index=False)
raw_input("data saved. Press enter")
答案 0 :(得分:0)
我能够找到错误的根源。它足够通用,可供其他人使用:
想象一下,你有一本字典:
import pandas as pd
newDF = {}
newDF["a"] = pd.Series([1,2,3])
newDF["b"] = pd.Series([2, 5 ,6])
newDF["c"] = pd.Series([3, 6, 9])
newDF =pd.DataFrame(newDF)
header = ["a" , "b", "c"] # these names must exactly match above
newDF.to_csv("file_data.csv", columns=header, sep=b'\t', float_format='%.5e', index=False)
但是如果其中一行被意外更改:
header = ["a" , "b", "c1"] # these names must exactly match above
将看到上述错误。