मान लीजिए आपके पास एक डेटाफ्रेम है और सकारात्मक और नकारात्मक दिशा में दो पीरियड्स द्वारा इंडेक्स शिफ्ट करने का परिणाम है:
shift the index by three periods in positive direction Id Age 2020-01-01 00:00:00 NaN NaN 2020-01-01 12:00:00 NaN NaN 2020-01-02 00:00:00 1.0 10.0 2020-01-02 12:00:00 2.0 12.0 2020-01-03 00:00:00 3.0 14.0 shift the index by three periods in negative direction Id Age 2020-01-01 00:00:00 3.0 14.0 2020-01-01 12:00:00 4.0 11.0 2020-01-02 00:00:00 5.0 13.0 2020-01-02 12:00:00 NaN NaN 2020-01-03 00:00:00 NaN NaN
समाधान
इसे हल करने के लिए, हम नीचे दिए गए चरणों का पालन करेंगे:
start='01-01-2020', periods=5, freq='12H' के साथ पांडास टाइम सीरीज़ बनाएं
एक डेटाफ्रेम परिभाषित करें
सकारात्मक दिशा में दो पीरियड्स द्वारा इंडेक्स शिफ्ट करने के लिए df.shift() लागू करें
df.shift(2, axis=0)
नकारात्मक दिशा में दो पीरियड्स द्वारा इंडेक्स शिफ्ट करने के लिए df.shift() लागू करें
df.shift(-2, axis=0)
उदाहरण
बेहतर समझ के लिए निम्न कोड देखें:
import pandas as pd
time_series = pd.date_range('01-01-2020', periods=5, freq='12H')
df = pd.DataFrame({"Id":[1,2,3,4,5],
"Age":[10,12,14,11,13]},
index=time_series)
print("Dataframe is:\n", df)
print("shift the index by three periods in positive direction")
print(df.shift(2, axis=0))
print("shift the index by three periods in negative direction")
print(df.shift(-2, axis=0))
आउटपुट
Dataframe is: Id Age 2020-01-01 00:00:00 1 10 2020-01-01 12:00:00 2 12 2020-01-02 00:00:00 3 14 2020-01-02 12:00:00 4 11 2020-01-03 00:00:00 5 13 shift the index by three periods in positive direction Id Age 2020-01-01 00:00:00 NaN NaN 2020-01-01 12:00:00 NaN NaN 2020-01-02 00:00:00 1.0 10.0 2020-01-02 12:00:00 2.0 12.0 2020-01-03 00:00:00 3.0 14.0 shift the index by three periods in negative direction Id Age 2020-01-01 00:00:00 3.0 14.0 2020-01-01 12:00:00 4.0 11.0 2020-01-02 00:00:00 5.0 13.0 2020-01-02 12:00:00 NaN NaN 2020-01-03 00:00:00 NaN NaN