हम पूरे डेटाफ्रेम को फिर से लिखे बिना पैंडास में shift() विधि का उपयोग करके डेटाफ्रेम के कॉलम को शिफ्ट कर सकते हैं। shift() निम्नलिखित पैरामीटर लेता है
shift(self, periods=1, freq=None, axis=0, fill_value=None)
- periods शिफ्ट करने के लिए अवधियों की संख्या। यह एक नकारात्मक संख्या भी ले सकता है।
- axis यह एक बूलियन मान लेता है; 0 यदि आप इंडेक्स शिफ्ट करना चाहते हैं और 1 यदि आप कॉलम शिफ्ट करना चाहते हैं
- fill_value यह लापता मान को प्रतिस्थापित करेगा।
आइए एक उदाहरण लें और देखें कि इस shift() विधि का उपयोग कैसे करें।
चरण
- दो-आयामी, आकार-परिवर्तनीय, संभावित विषम सारणीबद्ध डेटा, df बनाएं।
- इनपुट डेटाफ्रेम, df प्रिंट करें।
- एक कॉलम चुनें और df["column_name]=df.column_name.shift() का उपयोग करके इसे शिफ्ट करें
- अपडेटेड डेटाफ्रेम प्रिंट करें।
उदाहरण
import pandas as pd
df = pd.DataFrame(
dict(
name=['John', 'Jacob', 'Tom', 'Tim', 'Ally'],
marks=[89, 23, 100, 56, 90],
subjects=["Math", "Physics", "Chemistry", "Biology", "English"]
)
)
print("Input DataFrame is:\n", df)
df["name"] = df.name.shift(1)
print("After shifting column name by 1:\n", df)
df["marks"] = df.marks.shift(2)
print("After shifting column marks by 2:\n", df)
df["subjects"] = df.subjects.shift(-1)
print("After shifting column subjects by -1:\n", df)
आउटपुट
Input DataFrame is: name marks subjects 0 John 89 Math 1 Jacob 23 Physics 2 Tom 100 Chemistry 3 Tim 56 Biology 4 Ally 90 English After shifting column name by 1: name marks subjects 0 NaN 89 Math 1 John 23 Physics 2 Jacob 100 Chemistry 3 Tom 56 Biology 4 Tim 90 English After shifting column marks by 2: name marks subjects 0 NaN 100 Math 1 John 100 Physics 2 Jacob 89 Chemistry 3 Tom 23 Biology 4 Tim 100 English After shifting column subjects by -1: name marks subjects 0 NaN 100 Physics 1 John 100 Chemistry 2 Jacob 89 Biology 3 Tom 23 English 4 Tim 100 NaN