如果输入可被3和5整除,则用Python编写程序以移动第一列并从用户那里获取值,然后填充缺失的值

输入

假设您有一个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整除。如果结果为true,则填写缺少的值,否则填写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

猜你喜欢