编写Python程序以修剪数据框中的最小和最大阈值

假设您有一个数据框,并且修剪了最小和最大阈值,

minimum threshold:
   Column1 Column2
0    30    30
1    34    30
2    56    30
3    78    50
4    30    90
maximum threshold:
   Column1 Column2
0    12    23
1    34    30
2    50    25
3    50    50
4    28    50
clipped dataframe is:
   Column1 Column2
0    30    30
1    34    30
2    50    30
3    50    50
4    30    50

解决方案

为了解决这个问题,我们将遵循以下步骤-

  • 定义一个数据框

  • df.clip在内部应用函数(下限= 30)以计算最小阈值,

df.clip(lower=30)

  • df.clip在内部应用函数(上限= 50)以计算最大阈值

df.clip(upper=50)

  • 应用具有最小和最大阈值限制的裁剪数据帧,

df.clip(lower=30,upper=50)

例子

让我们检查以下代码以获得更好的理解-

import pandas as pd
data = {"Column1":[12,34,56,78,28],
         "Column2":[23,30,25,50,90]}
df = pd.DataFrame(data)
print("DataFrame is:\n",df)
print("minimum threshold:\n",df.clip(lower=30))
print("maximum threshold:\n",df.clip(upper=50))
print("clipped dataframe is:\n",df.clip(lower=30,upper=50))

输出

DataFrame is:
   Column1 Column2
0    12    23
1    34    30
2    56    25
3    78    50
4    28    90
minimum threshold:
   Column1 Column2
0    30    30
1    34    30
2    56    30
3    78    50
4    30    90
maximum threshold:
   Column1 Column2
0    12    23
1    34    30
2    50    25
3    50    50
4    28    50
clipped dataframe is:
   Column1 Column2
0    30    30
1    34    30
2    50    30
3    50    50
4    30    50

猜你喜欢