用 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