我试图读取以空格分隔的值,对其中一列应用Savitzky-Golay过滤器,将列四舍五入到6位小数,绘制图形并将数据导出到新文件。下面是工作代码,我注释掉了使图形窗口“不响应”的行:
import pandas as pd
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import savgol_filter
df = pd.read_csv('data.txt', delim_whitespace = True)
plt.plot(df.index, df.rotram, '-', lw=4)
#plt.plot(df.index, savgol_filter(df.rotram, 21, 3), 'r-', lw=2)
# smooth the 'rotram' column using Savitzky-Golay filter
df.rotram = savgol_filter(df.rotram, 21, 3)
# round to 6 decimal digits
#df.rotram = df.rotram.map('{:.6f}'.format) # <-- not responding when plotting
#df["rotram"] = df["rotram"].map('{:,.6f}'.format) # the same as above (not responding when plotting)
# When plot is removed then above rounding works well
plt.plot(df.index, df.rotram, 'r-', lw=2)
df.to_csv('filtered.txt', sep='\t')
plt.show()
print "End"
示例数据如下所示:
otklon rotram lakat rotnad
-6.240000 -3.317000 -34.445000 16.805000
-6.633000 -3.501000 -34.519000 17.192000
-5.099000 -2.742000 -34.456000 15.059000
-6.148000 -3.396000 -34.281000 17.277000
-4.797000 -3.032000 -34.851000 16.052000
-5.446000 -2.964000 -34.459000 15.677000
-6.341000 -3.490000 -34.934000 17.300000
-6.508000 -3.465000 -35.030000 16.722000
-6.513000 -3.505000 -35.018000 16.845000
-6.455000 -3.501000 -35.302000 16.896000
.
.
.
(more than 20000 lines)
输入文件中的分隔符是space + TAB + space
。你知道吗
如果我取消对行df.rotram = df.rotram.map('{:.6f}'.format)
的注释,那么程序将挂起(没有响应)空图形,尽管保存的数据是正确的。你知道吗
如果我删除行plt.plot(df.index, df.rotram, 'r-', lw=2)
,那么程序正常结束。你知道吗
虽然舍入后将数据保存到文件中效果很好,但打印不起作用:-/
如果要将列四舍五入到小数点后第n位,请使用
pd.Series.round
或np.around
:调用
map
时,将数值列转换为字符串。熊猫将绘制这些数据而不做任何假设。对于您的示例数据,绘图看起来很可怕:与之相比,后者使用
round
:图是完全不同的(在前一种情况下,每个字符串按字典顺序排序,并在y轴上给出自己的记号)。你知道吗
相关问题 更多 >
编程相关推荐