用 Python 編寫一個程式,對第一列進行移位操作,並從使用者獲取一個值。如果輸入的值同時能被 3 和 5 整除,則填充缺失的值。
輸入 -
假設您有一個 DataFrame,對第一列進行移位操作並填充缺失值的結果如下所示:
one two three 0 1 10 100 1 2 20 200 2 3 30 300 enter the value 15 one two three 0 15 1 10 1 15 2 20 2 15 3 30
解決方案
為了解決這個問題,我們將遵循以下方法。
定義一個 DataFrame
使用以下程式碼對第一列進行移位操作:
data.shift(periods=1,axis=1)
從使用者獲取值並驗證它是否同時能被 3 和 5 整除。如果結果為真,則填充缺失值,否則填充 NaN。定義如下:
user_input = int(input("enter the value"))
if(user_input%3==0 and user_input%5==0):
print(data.shift(periods=1,axis=1,fill_value=user_input))
else:
print(data.shift(periods=1,axis=1))示例
讓我們看看完整的實現以獲得更好的理解 -
import pandas as pd
data= pd.DataFrame({'one': [1,2,3],
'two': [10,20,30],
'three': [100,200,300]})
print(data)
user_input = int(input("enter the value"))
if(user_input%3==0 and user_input%5==0):
print(data.shift(periods=1,axis=1,fill_value=user_input))
else:
print(data.shift(periods=1,axis=1))輸出 1
one two three 0 1 10 100 1 2 20 200 2 3 30 300 enter the value 15 one two three 0 15 1 10 1 15 2 20 2 15 3 30
輸出 2
one two three 0 1 10 100 1 2 20 200 2 3 30 300 enter the value 3 one two three 0 NaN 1.0 10.0 1 NaN 2.0 20.0 2 NaN 3.0 30.0
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP