การจัดการและแสดงผลข้อมูลด้วย Python
pandas, cleaning flight-log data and plotting
Why it matters
A single drone flight produces a lot of data. The autopilot records altitude, position, battery voltage, motor output and flight mode many times per second. Together these records are the flight log. Read line by line, the numbers say little. Put into a table, cleaned and plotted, they answer practical questions: is the battery sagging faster than usual, is one motor working harder than the others, and when did the airframe start to vibrate?
This page gathers the ideas that several courses share: the data structures of pandas (the Python library for tabular data), a cleaning workflow, group summaries, and how to choose a chart that fits the question.
Tabular data in pandas
A DataFrame is a table in which every column has a name and its own data type. Think of it as a stricter spreadsheet. A single column is a Series, and each row carries a label called the index. The data type, or dtype, says whether a column holds floats, integers, text or timestamps. If a numeric column is read as text, every calculation that follows is wrong, so check df.dtypes after loading any file.
Data is easiest to analyse in tidy form: one row per observation, one column per variable, one table per topic. Autopilot logs are usually split into several tables by message type (battery, GPS, IMU and so on), each logged at its own rate. Those tables must be joined on time, never on row position.
Read and write text files that contain Thai with UTF-8 encoding. To change values, use df.loc[condition, "column"] = value as a single statement. pandas 3 enables Copy-on-Write by default, so chained assignment such as df[condition]["column"] = value no longer modifies the original table.
Cleaning the data
Data cleaning means finding and handling untrustworthy values before any analysis. Flight logs show four recurring problems.
- Duplicate rows, from merging a file twice or from repeated radio packets. Remove them with
drop_duplicates(). - Missing values, shown as
NaN, when a sensor did not report in that cycle. Count them withisna().sum(). - Outliers, values far from the rest. Some are real events, such as a gust. Others are sensor faults, such as 0 V from a battery in flight.
- Mismatched units and time bases, for example microseconds in one table and seconds in another, or altitude above the take-off point in one table and above mean sea level in another.
The rule is to decide from physics, not convenience. A 6-cell pack reading below 20 V during a normal hover is physically implausible and can be treated as an error. A value that is merely surprising should be kept and investigated. Record every correction (how many rows, which method) so that someone else can reproduce the result.
Interpolation fills a gap by drawing a straight line between the neighbouring samples and reading off the middle. It suits slowly changing signals such as altitude or voltage. It does not suit long gaps or fast signals such as IMU acceleration.
Worked example: a battery log with problems
Assume a 1 Hz log from a drone on a 6-cell battery, covering take-off and hover:
| t_s | alt_m | batt_v | mode | Problem |
|---|---|---|---|---|
| 0 | 0.0 | 25.1 | TAKEOFF | |
| 1 | 2.1 | 24.9 | TAKEOFF | |
| 2 | 4.0 | 24.8 | TAKEOFF | |
| 3 | 5.9 | 24.8 | LOITER | row appears twice |
| 4 | 6.0 | 0.0 | LOITER | 0.0 V is impossible in flight |
| 5 | 6.1 | 24.7 | LOITER | |
| 6 | (blank) | 24.7 | LOITER | altitude missing |
| 7 | 6.0 | 24.6 | LOITER | |
| 8 | 6.1 | 24.6 | LOITER |
The mean voltage of the 10 raw rows is 22.3 V. That looks alarming, because the nominal voltage of a 6-cell pack is 6 × 3.7 = 22.2 V. The mean has been dragged down by one 0.0 V reading. The cleaning steps are:
import numpy as np
import pandas as pd
df = pd.read_csv("flight_log.csv", encoding="utf-8")
print(len(df), round(df["batt_v"].mean(), 3)) # 10 rows, 22.3
df = df.drop_duplicates() # 9 rows left
df.loc[df["batt_v"] < 20, "batt_v"] = np.nan # 0.0 V is a sensor dropout
df["alt_m"] = df["alt_m"].interpolate()
df["batt_v"] = df["batt_v"].interpolate()
print(round(df["batt_v"].mean(), 3)) # 24.772
print(df.groupby("mode")["batt_v"].agg(["count", "mean", "min"]))
After removing the duplicate, marking 0.0 V as missing and interpolating, the mean becomes 24.772 V. The filled voltage is 24.75 V (halfway between 24.8 and 24.7) and the missing altitude becomes 6.05 m. Grouped by mode, TAKEOFF has 3 rows averaging 24.933 V and LOITER has 6 rows averaging 24.692 V, which makes sense for a pack that is slowly discharging. The conclusion changes from "battery nearly flat" to "battery normal, one sensor dropout", and the dropout belongs in the report.
df["alt_m"].diff() gives the change between consecutive rows: about 1.9 to 2.1 m per second during the climb and no more than 0.1 m per second in the hover. That is another plausibility check.
Group summaries and joins
The split-apply-combine pattern splits data into groups, computes something in each, and combines the results. In pandas this is groupby() followed by agg(), for example mean electrical power per flight mode or peak motor temperature per flight. With a time index, resample() lowers the rate (say, 50 Hz data to 1 s means), and rolling() gives moving means or moving medians to suppress noise.
To join tables logged at different rates, such as GPS at 5 Hz and battery at 10 Hz, use pd.merge_asof(), which pairs each row with the nearest earlier timestamp. Set a tolerance so that rows too far apart in time are not paired.
Choosing a chart
A good chart answers one question clearly. The usual library is Matplotlib, which pandas calls through df.plot().
| Question | Chart | Drone example |
|---|---|---|
| How does a value change over time? | Line chart, time on x | Battery voltage over a flight |
| Are two variables related? | Scatter plot | Electrical power against payload |
| How are values spread? | Histogram or box plot | GNSS position error |
| Which group is larger? | Bar chart | Mean flight time per battery model |
Every chart needs axis labels with units, such as "Voltage (V)" and "Time (s)". Several lines need a legend. Charts meant for comparison need the same axis scales. Anscombe's quartet shows that four data sets with almost identical means and correlations can look completely different, so plot before you summarise.
Common pitfalls
- Deleting outliers without a physical reason. Results look better than they are, and real events (a current spike before a motor failure) disappear.
- Joining tables by row order when their logging rates differ. Join on time.
- Not checking dtypes. A numeric column with stray symbols or spaces is read as text.
- Chained assignment, which has no effect in pandas 3. Use one
.locstatement. - One mean for a whole flight, even though take-off, cruise and hover draw very different power. Summarise by mode or phase.
- Charts without units, or with a truncated axis that is not flagged, which misleads the reader about the size of a difference.
- Editing the original log. Keep the raw file and clean it with a script that can be rerun.
Continue in the lessons
Key references
- McKinney, W. (2022). Python for data analysis (3rd ed.). O'Reilly. link
- The pandas development team. (2026). What’s new in 3.0.0. pandas documentation. link
- The Matplotlib development team. Matplotlib documentation (3.11). link
- Anscombe, F. J. (1973). Graphs in statistical analysis. The American Statistician, 27(1), 17–21. link
- PX4 Autopilot. pyulog: Python module to parse ULog files (version 1.2). link