ডেটাফ্রেমে নেগেটিভ মানগুলোকে তার আগের নিকটতম পজিটিভ মান (forward fill) দিয়ে প্রতিস্থাপন করা হয়। যদি কোনো পজিটিভ মান না থাকে, তবে ০ দিয়ে ফিল করা হয়।
ইনপুট ডেটা
One two
0 -3 -6
1 7 -1
2 4 2
3 0 -8
পদ্ধতি: mask() + ffill() + fillna()
import pandas as pd
df = pd.DataFrame({'One': [-3, 7, 4, 0], 'two': [-6, -1, 2, -8]})
print("মূল ডেটাফ্রেম:")
print(df)
# ১. নেগেটিভ মানগুলোকে NaN এ রূপান্তর (mask)
# ২. ffill() — আগের ভ্যালু ফরওয়ার্ড ফিল
# ৩. fillna(0) — শুরুর NaN গুলো ০ দিয়ে ফিল
# ৪. astype('int32') — ইন্টিজারে রূপান্তর
df = df.mask(df.lt(0)).ffill().fillna(0).astype('int32')
print("\nআপডেটেড ডেটাফ্রেম:")
print(df)
আউটপুট
মূল ডেটাফ্রেম:
One two
0 -3 -6
1 7 -1
2 4 2
3 0 -8
আপডেটেড ডেটাফ্রেম:
One two
0 0 0
1 7 0
2 4 2
3 0 2
স্টেপ-বাই-স্টেপ ব্যাখ্যা
# স্টেপ ১: নেগেটিভ কে NaN
masked = df.mask(df.lt(0))
print(masked)
# One two
# 0 NaN NaN
# 1 7.0 NaN
# 2 4.0 2.0
# 3 0.0 NaN
# স্টেপ ২: ফরওয়ার্ড ফিল
ffilled = masked.ffill()
print(ffilled)
# One two
# 0 NaN NaN
# 1 7.0 NaN
# 2 4.0 2.0
# 3 0.0 2.0
# স্টেপ ৩: বাকি NaN ০ দিয়ে ফিল
filled = ffilled.fillna(0)
print(filled)
# One two
# 0 0.0 0.0
# 1 7.0 0.0
# 2 4.0 2.0
# 3 0.0 2.0
বিকল্প: numpy.where ব্যবহার
import numpy as np
df = df.where(df >= 0).ffill().fillna(0).astype(int)
# where(condition) — condition True হলে মান রাখে, False হলে NaN
উভয় পদ্ধতিই সমান ফলাফল দেয়। mask = where(~condition)।