[英]Average for similar looking data in a column using Pandas
我正在處理超過 60K 行的大型數據。
我在列中連續測量電流。 一個代碼被測量一秒鍾,設備測量它 14/15/16/17 次,具體取決於設備速度,然后測量移動到下一個代碼並再次測量 14/15/16/17 次,依此類推向前。 每次測量從一個代碼移動到另一個代碼時,當前測量值都會有超過0.15的跳躍
前48行的數據如下,
指數 | 電流(mA) |
---|---|
0 | 1.362476 |
1 | 1.341721 |
2 | 1.362477 |
3 | 1.362477 |
4 | 1.355560 |
5 | 1.348642 |
6 | 1.327886 |
7 | 1.341721 |
8 | 1.334804 |
9 | 1.334804 |
10 | 1.348641 |
11 | 1.362474 |
12 | 1.348644 |
13 | 1.355558 |
14 | 1.334805 |
15 | 1.362477 |
16 | 1.556172 |
17 | 1.542336 |
18 | 1.549252 |
19 | 1.528503 |
20 | 1.549254 |
21 | 1.528501 |
22 | 1.556173 |
23 | 1.556172 |
24 | 1.542334 |
25 | 1.556172 |
26 | 1.542336 |
27 | 1.542334 |
28 | 1.556170 |
29 | 1.535415 |
30 | 1.542334 |
31 | 1.729109 |
32 | 1.749863 |
33 | 1.749861 |
34 | 1.749861 |
35 | 1.736024 |
36 | 1.770619 |
37 | 1.742946 |
38 | 1.763699 |
39 | 1.749861 |
40 | 1.749861 |
41 | 1.763703 |
42 | 1.756781 |
43 | 1.742946 |
44 | 1.736026 |
45 | 1.756781 |
46 | 1.964308 |
47 | 1.957395 |
我想編寫一個腳本,其中 14/15/16/17 次的類似數據在每個代碼測量的單獨列中平均。我一直在考慮用 pandas 來做這件事。
我希望數據看起來像
指數 | 電流(mA) |
---|---|
0 | 1.34907 |
1 | 1.54556 |
2 | 1.74986 |
需要一些幫助才能完成這項工作。 請幫忙
首先獲取有跳轉的每一行的索引。 使用 Pandas 的DataFrame.diff()
獲取每行與前一行的值之間的差異,然后使用>
檢查它是否大於0.15
。 使用它來過濾 dataframe 索引,並將結果索引(在示例數據的情況下為三個)保存在變量中。
indices = df.index[df['Curr(mA)'].diff() > 0.15]
接下來的步驟取決於源 dataframe 中是否有您想要在 output 中的更多列,或者它是否真的只是curr(mA)
和索引。 在后一種情況下,您可以使用np.split()
根據您剛剛提取的索引將 dataframe 切割成數據幀列表。 然后你可以提前 go 並在列表中平均它們。
[df['Curr(mA)'].mean() for df in np.split(df, indices)]
> [1.3490729374999997, 1.5455638666666667, 1.7498627333333332, 1.9608515]
為了讓它與您想要的 output 匹配(相同但與單列 dataframe 而不是列表)將列表轉換為pd.Series
和reset_index()
。
pd.Series(
[df['Curr(mA)'].mean() for df in np.split(df, indices)]
).reset_index(drop=True)
index 0
0 0 1.349073
1 1 1.545564
2 2 1.749863
3 3 1.960851
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.