如何在Python的DataFrame中按指定步长将指定列的部分值替换为NaN
Solution for Replacing Lat Values with NaN in Step Pattern
Hey there! Let's work through this problem together. You want to keep every 3rd row's Lat value starting from the first one, and set the next two rows to NaN—here's a simple, efficient way to do this with pandas:
Step 1: Import Required Libraries
First, make sure you have pandas and numpy ready:
import pandas as pd import numpy as np
Step 2: Set Up Your Sample DataFrame
Let's start with the dataset you provided:
data = { 'N': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'Lat': [37.536866, 37.536867, 37.536868, 37.536868, 37.536869, 37.536869, 37.536870, 37.536871, 37.536871], 'Long': [15.068850] * 9 } df = pd.DataFrame(data)
Step 3: Apply the Replacement Logic
We'll use pandas' where() method to retain Lat values only in rows where N modulo 3 equals 1 (since you want to keep rows N=1, 4, 7...). For all other rows, we'll replace Lat with NaN:
df['Lat'] = df['Lat'].where(df['N'] % 3 == 1, np.nan)
Step 4: Verify the Result
If you print the DataFrame now, you'll get exactly the output you're looking for:
print(df)
Output:
N Lat Long 0 1 37.536866 15.068850 1 2 NaN 15.068850 2 3 NaN 15.068850 3 4 37.536868 15.068850 4 5 NaN 15.068850 5 6 NaN 15.068850 6 7 37.536870 15.068850 7 8 NaN 15.068850 8 9 NaN 15.068850
Quick Explanation
- The
where()method keeps the original value when the condition (df['N'] % 3 == 1) is true, and replaces it withnp.nanwhen false. - Tying the logic directly to your
Ncolumn makes the code intuitive and easy to tweak if your step pattern changes later.
内容的提问来源于stack exchange,提问作者gcicceri
相关产品推荐
相关产品推荐

