python - 舍入数据框列后的绘图不起作用

标签 python pandas matplotlib formatting

我正在尝试读取空格分隔值,将 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)

输入文件中的分隔符为空格 + TAB + 空格

如果我取消注释行df.rotram = df.rotram.map('{:.6f}'.format),那么程序会挂起(没有响应)并显示空图保存的数据正确

如果我删除行 plt.plot(df.index, df.rotram, 'r-', lw=2) 那么程序会正常结束。

虽然舍入后将数据保存到文件效果很好,但绘图却不行:-/

最佳答案

如果要将列四舍五入到小数点后第 N 位,请使用 pd.Series.roundnp.around:

df.rotram = df.rotram.round(decimals=6)
# Or,
# df.rotram = np.around(df.rotram, decimals=6)
<小时/>

However, I would still like to know why the above code doesn't work as expected.

当您调用map时,您将数字列转换为字符串。 Pandas 将绘制这些数据而不做任何假设。对于您的示例数据,该图看起来很丑陋:

enter image description here

对比,后一种情况使用round:

enter image description here

绘图完全不同(在前一种情况下,每个字符串按字典顺序排序,并在 y 轴上给出自己的刻度)。

关于python - 舍入数据框列后的绘图不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53244369/

相关文章:

python Pandas : list of integers as individual values of DataFrame

python - 测试两个线段是否大致共线(在同一条线上)

Python:如何找到最频繁的元素组合?

python - 读取具有超过 1 个条目的列的数据

python - 如何使用 numpy 创建范围的二维数组

python - Pandas 在日期时间多索引框架上滚动

python - Pandas 洗牌列值不起作用

python - 如何在不同的子图中绘制 pcolor colorbar - matplotlib

python - 对直方图中绘制的给定数据标准化威 bool 分布

Python-实时传感器数据绘图