我有以下資料框:
0 5 15 20 25 30 35 40 45 50
----------------------------------------------
0 85 75 65 52 39 21 12 5 2 0
1 80 69 52 48 21 12 5 2 0 0
2 81 68 61 49 32 25 14 4 1 0
3 82 64 43 32 19 5 0 0 0 0
4 79 64 49 41 22 6 2 0 0 0
就背景關系而言,每一列和每列的數字標題表示距站點的距離(以英尺為單位)。因此,對于每一行,我都在測量某個值如何隨著與站點距離的增加而減小。每行將是一條單獨的曲線。因此,我可以使用 matplotlib 將每條曲線繪制為單獨的圖,從而為每條曲線(行)生成 5 個單獨的圖。那部分很容易。
但是,由于我在每一行中都有 0,并且在所有情況下都是多個 0,因此 0 點將包含在圖中。對于具有多個 0 的行,所有 0 都記錄在圖中,因此這些圖的尾部為 0,x 軸一直延伸到 50 英尺。與這些圖只有一個 0 值相比,這將創建一條不同形狀的曲線。就背景關系而言,在我的資料/實驗中,在命中 0 后永遠不會有任何值增加,因此額外的 0 的尾部是不必要的,而只是用于給出一個麻煩的形狀曲線(0 的尾部而不是單個 0 )。因此,具有多個零的行作為尾部為 0 的曲線會產生不同形狀的曲線,而不是那些曲線中僅包含一個 0。我想要做的是找到一種方法來消除行中那些額外的零,這樣一旦曲線達到 0,
就背景關系而言,我在這里嘗試做的最終任務是將不同的曲線方程擬合到這些曲線上。我想使用僅包含第一個 0 的曲線,而不是多個 0 的尾部。到目前為止,我一直試圖將額外的 0 分類為 NaN,但是當我嘗試繪制這個時,我得到了一個ValueError: array must not contain infs or NaNs錯誤。我怎樣才能正確地去除每行第一個 0 之后的額外 0,以便額外的零沒有在曲線圖中表示?
uj5u.com熱心網友回復:
如果您只想保留第一個 0 而不是 0 的尾跡,您可以使用 numpy 的函式nonzero來查找非零值的索引并修剪陣列以包含這些值加上第一個 0。這適用于繪圖和資料操作。
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame({'0': [85, 80, 81, 82, 79],
'5': [75, 69, 68, 64, 64],
'15': [65, 52, 61, 43, 49],
'20': [52, 48, 49, 32, 41],
'25': [39, 21, 32, 19, 22],
'30': [21, 12, 25, 5, 6],
'35': [12, 5, 14, 0, 2],
'40': [5, 2, 4, 0, 0],
'45': [2, 0, 1, 0, 0],
'50': [0, 0, 0, 0, 0]})
# Initiate figure
fig, axs = plt.subplots(nrows=5, ncols=1, sharex='col')
for row in df.index:
# Get array for plotting
values = np.array(df.loc[row])
make_x = np.array([0, 5, 15, 20, 25, 30, 35, 40, 45, 50])
# Count number zeros values
number_zeros = len(values) - np.count_nonzero(values)
# There is more than one 0s - aka there is a tail of 0s in this array
if number_zeros > 1:
# Get index of last value that is not nonzero in the array
end_idx = np.nonzero(values)[0][-1] 2
# Note: the 2 is because you want the first 0 after the last nonzero value (so you add 1 to index count) but in python the last index is not included so you want the index after that so that the first 0 is included (another 1, therefore 2)
# Trim the array to only include one zero
values = values[0:end_idx]
make_x = make_x[0:end_idx]
axs[row].plot(make_x, values)
axs[0].set_ylim([0, 90])
plt.show()
這是每個圖只有一個 0 的結果:

希望這會有所幫助,干杯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/497794.html
標籤:Python 熊猫 麻木的 matplotlib
上一篇:在字典串列上映射字典。如何在沒有for回圈的情況下優化它?
下一篇:如何精確比較嵌套For回圈中的值
