用 Python 编写一个程序,移动第一列并从用户那里获取值,如果输入可以被 3 和 5 整除,则填充缺失值
pythonpandasserver side programmingprogramming更新于 2024/6/21 6:36:17
输入 −
假设您有一个 DataFrame,移动第一列并填充缺失值的结果是,
one two three 0 1 10 100 1 2 20 200 2 3 30 300 输入值 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("输入值"))
if(user_input%3==0 and user_input%5==0):
print(data.shift(periods=1,axis=1,fill_value=user_input))
否则:
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("输入值"))
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 输入值 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 输入值 3 one two three 0 NaN 1.0 10.0 1 NaN 2.0 20.0 2 NaN 3.0 30.0
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

