python - 为 DataFrame 列中的值设置上限和下限

标签 python pandas dataframe

我有以下列:

 Column 1
 1
 10
 5
 100
 50
 1000
 50000
 2000
 100
 1000
 3000
 ...

我想为 Col1 中值 >= 1000 的每一行分配 Col 2 中的值 1000,为每个值 <= 100 分配值 100。

 Column 1   Column 2
 1          100
 10         100
 5          100
 100        100
 50         100
 1000       1000
 50000      1000
 2000       1000
 100        100
 1000       1000
 3000       1000
 ...

我该怎么做?

最佳答案

您可以使用 clip :

>>> df['Column 2'] = df['Column 1'].clip(100, 1000)
>>> df
    Column 1  Column 2
0          1       100
1         10       100
2          5       100
3        100       100
4         50       100
5       1000      1000
6      50000      1000
7       2000      1000
8        100       100
9       1000      1000
10      3000      1000

所有小于100的值都设置为100;所有大于 1000 的值都设置为 1000。

关于python - 为 DataFrame 列中的值设置上限和下限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30578705/

相关文章:

Python 相当于 R 的 mclapply()

python - 访问 MultiIndexed groupby 的键

python - Pandas DataFrame 构造函数对行进行排序,即使使用 OrderedDict 作为输入

python - 将 MultiIndex 列合并为 1 级

python - 特拉维斯 CI : Switch to python 3 temporarily

python - Pyspark JSON 对象或文件到 RDD

python - 将列标题添加到 pandas 数据框..但是 NAN 是所有数据,即使标题是相同的维度

python - 根据多元列值删除 Pandas 中的 DataFrame 行

python - 使用 Flask 从静态之外的目录提供文件

python - P4Python 问题 : p4run ("files", 'path' )返回 - 没有这样的文件,尽管返回 "dirs"的单个项目字典