Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

2.4 DataFrame Exploration and Cleaning

Before any modeling, you need to know what is in your table. This lesson walks through a standard preparation pipeline on a pandas DataFrame: read the data, inspect types and summary statistics, handle missing values, decide what each zero means, and explore correlations and per-class distributions.

The dataset is a synthetic whole-rock geochemistry table generated by the course package mlgeo_synth, shaped like an extract from archives such as EarthChem or GEOROC. Each row is one rock sample with:

  • Major-element oxides (SIO2, AL2O3, FEO, MGO, CAO, NA2O, K2O) in weight percent (wt%). Treat FEO as total iron reported as FeO, often written FeOT; real archives mix FeO, Fe2O3 and FeOT, and you must know which one a table holds before comparing it with another. Only seven oxides are reported (TiO2, MnO, P2O5 and loss on ignition are absent), so the rows do not sum to 100 wt%.

  • density_g_cm3: bulk density in g/cm3,

  • mag_susc_si: magnetic susceptibility (SI units),

  • label: the lithology (granite, basalt, andesite), which a classifier would later try to predict.

🧪 Sample & laboratory · 🪨 Solid Earth · ⛰️ Geology & geomorphology (synthetic)

The samples have no locations, so this lesson has no map; a real extract would carry latitude, longitude and the source publication for every row. Real archives also rarely hold chemistry and petrophysics for the same sample: building a table like this one means joining two databases by sample identifier, a pipeline step with checks of its own.

The generator plants the relationships: a latent differentiation index drives the oxides, so SiO2 anticorrelates with FeO, MgO and CaO, and density tracks the mafic oxides. It also sets every negative oxide value to exactly zero, which you will meet in section 3. Your job is to find these properties in the table and to decide, column by column, what each value means.

🖥️ Lecture slides — Session 05 (Fri Oct 9)

1. Read and Explore the Data

Loading...
<class 'pandas.DataFrame'>
RangeIndex: 10000 entries, 0 to 9999
Data columns (total 10 columns):
 #   Column         Non-Null Count  Dtype  
---  ------         --------------  -----  
 0   SIO2           10000 non-null  float64
 1   AL2O3          10000 non-null  float64
 2   FEO            10000 non-null  float64
 3   MGO            10000 non-null  float64
 4   CAO            10000 non-null  float64
 5   NA2O           10000 non-null  float64
 6   K2O            10000 non-null  float64
 7   density_g_cm3  10000 non-null  float64
 8   mag_susc_si    10000 non-null  float64
 9   label          10000 non-null  str    
dtypes: float64(9), str(1)
memory usage: 847.3 KB

The column label holds strings, everything else is numeric. Check the summary statistics next. Read the min and max rows against physical expectations: oxides should sit between 0 and 100 wt%, and crustal rock densities between roughly 2.5 and 3.3 g/cm3. Geochemists run one more check on every analysis, the oxide total: a complete major-element analysis sums to about 100 wt%. This table reports only seven oxides, so its totals are lower and the check cannot be applied as is; the exercise asks you to look at them anyway.

Loading...
label granite 5525 basalt 3490 andesite 985 Name: count, dtype: int64

The classes are imbalanced: granites outnumber andesites by more than five to one. Keep that number in mind; it comes back in the exercise.

2. Handling Missing Values (NaNs)

Field and lab datasets have gaps: a sensor fails, a lab skips an analysis, a value is dropped during transcription. In pandas, missing values appear as NaN or the newer pd.NA. Common strategies:

  • Remove rows/columns with missing values: fine when the missing fraction is small and missingness is unrelated to the value itself.

  • Impute: fill gaps with a mean, median, interpolation, or a model-based estimate. Imputation keeps sample size but injects assumptions.

This synthetic table comes out of the generator complete, which real data never is. To give the lesson something to clean, we deliberately knock out a small random fraction of the density and magnetic susceptibility measurements, and we set a few density values to 0 to mimic an instrument that writes 0 when a measurement fails. This kind of “sentinel” zero is common in real archives.

SIO2               0
AL2O3              0
FEO                0
MGO                0
CAO                0
NA2O               0
K2O                0
density_g_cm3    187
mag_susc_si      302
label              0
dtype: int64

Note the modern pandas style used above: we assign with df.loc[mask, col] = value and reassign results (df = df.something()) instead of using inplace=True on views or slices. Chained inplace operations on a slice of a DataFrame raise errors in pandas 3.

3. Zeros: measured values, values below detection, or missing-data codes

A tempting shortcut is “replace all zeros with NA”. Do not do this. What a zero means depends on the variable and on how it was measured:

  • An oxide reported as exactly 0.00 wt% is not a measured zero. Every analysis has a detection limit, and a laboratory or database that writes 0 means “below the detection limit” or “not analyzed”. Real rocks can be low in an oxide (evolved granites have little MgO left; many basalts have little K2O) but they are not free of it. These values are censored: the true value lies somewhere between zero and the detection limit (section 5). In this synthetic table the zeros come from the generator, which sets every negative draw to exactly zero and records no detection limit, so treat the limit as unknown.

  • A density of 0 g/cm3 is impossible. No rock has zero density. A zero there is a sentinel: a code some instrument or database used to mean “no measurement”.

The check is simple: count zeros per column and ask, for each column, whether zero is a possible measurement, a value below detection, or a code.

SIO2                0
AL2O3               0
FEO               184
MGO              1434
CAO               367
NA2O                0
K2O               824
density_g_cm3      15
mag_susc_si         0
dtype: int64

Thousands of oxide zeros, and exactly the 15 density zeros we planted. Now look at which rocks carry the MgO zeros.

label
granite     1432
andesite       2
Name: count, dtype: int64

Median SiO2 of MgO=0 samples: 74.2 wt%
Median SiO2 of the full table: 69.2 wt%

The MgO zeros are almost all granites, and silica-rich ones: the rocks where MgO is expected to be lowest. That makes them informative, but not as measured zeros. They say “below detection” in exactly the samples where low MgO is real. Converting them to missing and dropping the rows would remove the most evolved granites and shift the granite SiO2 distribution; using them as true zeros in a calculation pulls the granite mean MgO down. So keep the rows, flag the values as below detection, and write in your cleaning log that the detection limit is unknown. Check the K2O zeros yourself: they sit in the opposite rock type, the basalts, where K2O is low.

The density zeros are a different story. Replace only those with pd.NA, by assignment, not inplace.

SIO2               0
AL2O3              0
FEO                0
MGO                0
CAO                0
NA2O               0
K2O                0
density_g_cm3    202
mag_susc_si      302
label              0
dtype: int64

density dtype after replace: object

Look at the dtype: replace with pd.NA silently upcast the column from float64 to object. That matters, because every select_dtypes(include='number') call downstream — the correlation matrices, describe() — would silently drop density, the very column this cleaning was protecting. A column can be numeric in content and non-numeric in dtype, and pandas will not warn you. Cast it back before moving on, and make dtype checks part of every cleaning step, not just the first one.

density dtype after cast: float64

4. Dropping the Incomplete Rows

The missing fraction is small (about 5% of rows have at least one gap) and, by construction here, unrelated to the values themselves, so dropping is defensible. With real data you would first ask why values are missing before dropping anything.

Rows before: 10000, after dropping incomplete rows: 9499
<class 'pandas.DataFrame'>
Index: 9499 entries, 0 to 9999
Data columns (total 10 columns):
 #   Column         Non-Null Count  Dtype  
---  ------         --------------  -----  
 0   SIO2           9499 non-null   float64
 1   AL2O3          9499 non-null   float64
 2   FEO            9499 non-null   float64
 3   MGO            9499 non-null   float64
 4   CAO            9499 non-null   float64
 5   NA2O           9499 non-null   float64
 6   K2O            9499 non-null   float64
 7   density_g_cm3  9499 non-null   float64
 8   mag_susc_si    9499 non-null   float64
 9   label          9499 non-null   str    
dtypes: float64(9), str(1)
memory usage: 880.1 KB
SIO2             0
AL2O3            0
FEO              0
MGO              0
CAO              0
NA2O             0
K2O              0
density_g_cm3    0
mag_susc_si      0
label            0
dtype: int64

label
granite     5182
basalt      3357
andesite     960
Name: count, dtype: int64

5. Censored values

Missing values announce themselves: isna() finds them. A censored value does not: the instrument reports a number, and the number is wrong in a systematic way. The classic case is a detection limit: below it, a laboratory writes the limit itself (“<0.01 wt%” becomes 0.01) or a zero, and a stream gauge reports its lowest rated flow. The oxide zeros in section 3 are censored values of this kind.

To measure what censoring does to a statistic, you need the uncensored truth, which no real archive provides. So we impose a floor on a synthetic series whose truth we keep: mlgeo_synth.degrade_series does this on a GNSS-shaped displacement series. Be clear about the example. A real GNSS position has no reporting floor (displacements are relative to a reference epoch and can be negative); the floor is imposed here only to make the bias measurable. The real cases are laboratory detection limits for trace elements, nutrients and contaminants, and gauges at low flow.

<Figure size 1200x380 with 2 Axes>
fraction of samples censored: 0.120
trend fit on reported values:   11.59 mm/yr
trend fit on uncensored values: 12.44 mm/yr

Three signatures to remember. First, isna() reports zero missing values: censored data passes every missingness check. Second, the histogram has a spike of identical values exactly at the limit — a spike at a suspiciously round number is the fingerprint of censoring (just as the density zeros were the fingerprint of a sentinel code). Third, statistics are biased in a predictable direction: the reported first-year mean is too high, and the fitted trend is too low, because every low excursion was pulled up to the floor. Dropping the censored samples does not fix this either: it removes exactly the low values. Try it in the exercise: the year-1 mean moves further from the truth, and the trend moves only part of the way back, so which statistic gets worse depends on what you compute. The honest options are to model the censoring (survival/tobit methods) or to report the limit alongside the data, as lesson 2.13’s data card requires.

A related trap is the mid-record instrument change: a new sensor with a lower detection limit, or a relocated gauge, changes the statistics of the record without any change in the physics. A step in a record’s variance or minimum value is a question for the station metadata before it is a scientific result.

Informative missingness

Section 4 dropped rows on the argument that the gaps were “unrelated to the values themselves” — true here by construction, because we planted them at random (the statisticians’ term is missing completely at random, MCAR). Real instruments rarely oblige. The stream gauge drowns during the flood it was supposed to measure; the GNSS antenna goes silent under the winter storm’s snow load; the field crew skips the site when the road washes out. In each case the value is missing because of the value that would have been measured (missing not at random, MNAR), and dropping those rows systematically deletes the extremes — the floods, the storms — that the analysis probably cares most about. The MgO zeros earlier in this lesson follow the same logic: the values below detection sit in the most evolved granites, so removing those rows would have rewritten the geology. Before dropping or imputing anything, ask what process created the gap. If the answer involves the measured quantity, the missingness is itself data, and it belongs in the missing-data policy of your data card.

6. Correlation Analysis

Correlations between features tell you which measurements carry redundant information and hint at the physics behind the table. We compute two matrices:

  • Pearson correlation measures linear relationships.

  • Spearman rank correlation measures monotonic relationships. It is robust to outliers and to nonlinear but monotonic links, which are common in geochemistry.

The label column is a string, so first keep only the numeric columns.

Loading...
<Figure size 1000x800 with 2 Axes>
<Figure size 1000x800 with 2 Axes>

Read the two matrices side by side. SiO2 is strongly anticorrelated with FeO, MgO, and CaO, and positively correlated with K2O. Density tracks the mafic oxides and anticorrelates with SiO2. Where the Spearman value is noticeably stronger than the Pearson value, the relationship is monotonic but not linear; magnetic susceptibility is a typical case, since it spans orders of magnitude.

Two cautions before you read these numbers as petrology.

First, the matrices pool three rock suites. Much of the SiO2-CaO correlation of about −0.99 comes from the differences between the class means (basalts low in SiO2 and high in CaO, granites the reverse); within each lithology the same correlation is weaker, about −0.8. A correlation pooled across groups can be strong even when the relationship inside each group is weak, or of opposite sign. The exercise asks you to compute it.

Second, real major-element analyses are compositional data: a complete analysis sums to about 100 wt%, so if one oxide goes up, others must come down, and this closure builds negative correlation into a table regardless of any petrology (Chayes, 1960, Chayes (1960)). This synthetic table is not closed: its seven oxides sum to anywhere between about 90 and 105 wt% (check it in the exercise), and every correlation in it was planted by the generator. Real tables do carry closure; the usual remedy is to analyze log-ratios of components rather than raw percentages.

7. Feature Distributions per Lithology

Correlation matrices pool all classes together. To see which features separate the lithologies, plot each feature’s distribution per class.

One caution about the labels. Volcanic rocks are often named from their SiO2 and total alkalis, using the TAS classification (Le Bas et al., 1986, BAS et al. (1986)), so in a real archive a feature like SiO2 may separate the labels because it was used to define them. In this synthetic table the label generated the chemistry, the reverse of that situation. Granite is a plutonic rock name; its volcanic equivalent is rhyolite, and chemistry alone cannot tell the two apart.

<Figure size 1500x1200 with 9 Axes>
<Figure size 1500x1200 with 9 Axes>

Some features separate the classes almost completely; others overlap heavily. Some distributions look roughly Gaussian, others are skewed or heavy-tailed. To quantify shape, compute skewness and kurtosis alongside the usual moments.

Granite:
            SIO2   AL2O3    FEO    MGO    CAO   NA2O    K2O  density_g_cm3  \
mean      72.043  13.981  2.481  0.947  1.799  3.511  4.213          2.650   
median    72.040  13.977  2.477  0.756  1.753  3.503  4.210          2.649   
std        2.128   0.677  1.319  0.930  1.129  0.672  0.785          0.037   
skewness  -0.007  -0.001  0.180  0.880  0.332 -0.003  0.033         -0.006   
kurtosis   0.015   0.121 -0.326  0.191 -0.370  0.061 -0.067          0.058   

          mag_susc_si  
mean            0.000  
median          0.000  
std             0.000  
skewness        1.796  
kurtosis        5.938  

Basalt:
            SIO2   AL2O3     FEO    MGO     CAO   NA2O    K2O  density_g_cm3  \
mean      48.931  15.014  10.044  7.547  11.032  2.479  0.677          2.951   
median    48.976  15.028  10.029  7.564  11.025  2.470  0.571          2.951   
std        2.121   0.681   1.367  1.187   1.187  0.690  0.631          0.036   
skewness   0.001  -0.002   0.017 -0.031  -0.038  0.053  0.854          0.023   
kurtosis   0.083   0.001   0.087 -0.040   0.079 -0.025  0.352         -0.105   

          mag_susc_si  
mean            0.001  
median          0.001  
std             0.001  
skewness        1.616  
kurtosis        4.949  

Andesite:
            SIO2   AL2O3    FEO    MGO    CAO   NA2O    K2O  density_g_cm3  \
mean      58.910  17.041  6.544  3.545  6.553  3.779  1.775          2.798   
median    58.943  17.050  6.519  3.504  6.565  3.761  1.780          2.798   
std        2.142   0.681  1.381  1.227  1.169  0.668  0.791          0.036   
skewness  -0.009  -0.093  0.044  0.155 -0.063  0.117  0.061         -0.062   
kurtosis  -0.132   0.117 -0.235 -0.032 -0.089 -0.085 -0.206          0.151   

          mag_susc_si  
mean            0.001  
median          0.000  
std             0.000  
skewness        3.393  
kurtosis       27.926  

Skewness near 0 and kurtosis near 0 (scipy uses the excess-kurtosis convention) indicate a roughly Gaussian shape. Large positive skewness, as in magnetic susceptibility, signals a heavy right tail; such features are often log-transformed before modeling.

Save the cleaned table for later chapters.

Loading...

8. Exercise

Answer with code and a short written justification for each question.

  1. Pooled and within-class correlations. From the Pearson matrix, list the three strongest anticorrelations with SiO2. Then compute the same correlations within each lithology. How much of each pooled value comes from the differences between classes? Finally, compute the seven-oxide total for every row and describe its distribution: does this table show the closure that complete analyses have, and what would you need in order to test for closure in a real table?

  2. Best separating feature. Using the per-class histograms and the summary statistics, which single feature best separates the three lithologies? Support your choice quantitatively, for example by comparing the difference in class means to the class standard deviations for each feature. Then explain why, in a real archive, the answer may partly reflect how the labels were defined (section 7).

  3. Class imbalance. Granites make up more than half the table and andesites about 10%. If you trained a classifier on this table and measured only overall accuracy, what accuracy would a model that always predicts “granite” achieve? What does that imply about how you should evaluate a future classifier on this dataset?

  4. Values below detection. Suppose a colleague hands you a version of this table where all MgO zeros were replaced with NaN and the rows dropped. Which class would lose the most samples, and how would the SiO2 distribution of the remaining granites change? Now suppose they instead replaced each MgO zero with half of an assumed detection limit of 0.1 wt%, a common substitution. How does the granite mean MgO change compared with keeping the zeros, and what would you write in the cleaning log?

References
  1. Chayes, F. (1960). On correlation between variables of constant sum. Journal of Geophysical Research, 65(12), 4185–4193. 10.1029/jz065i012p04185
  2. BAS, M. J. L., MAITRE, R. W. L., STRECKEISEN, A., & ZANETTIN, B. (1986). A Chemical Classification of Volcanic Rocks Based on the Total Alkali-Silica Diagram. Journal of Petrology, 27(3), 745–750. 10.1093/petrology/27.3.745