【问题标题】:Python Round Dataframe Columns with Specific Value If Exists具有特定值的 Python 圆形数据框列(如果存在)
【发布时间】:2019-10-24 10:51:19
【问题描述】:

我的输入数据框;

A       B 
0.3     0.6
0.4     3.05
1.6     4.35
0.15    5.47
4.19    9.99

如果存在,我想根据特定值舍入我的数据框列。我的代码如下所示;

rounding=0.25

df['A']=round(df['A'] - rounding + 0.5)
df['B']=round(df['B'] - rounding + 0.5)

输出是;

A    B
1    1
1    3
2    5
0    6
4    10

问题是如果没有“舍入”变量,它应该默认自动运行(0.5)。 我需要一个可以同时运行的代码。类似或不同的东西;

if rounding==rounding:
    df['A']=round(df['A'] - rounding + 0.5)

else:
    df['A']=round(df['A'])

我看到了很多关于具有特定值的四舍五入的主题,但我看不到这一点。

你能帮我解决这个问题吗?

【问题讨论】:

  • the issue is if there is no "rounding" variable - 怎么可能?你能解释更多吗?
  • “舍入”变量可能会也可能不会。如果不存在,它应该接受默认的圆形值,即 0.5
  • 是的,但怎么可能不存在?我不清楚。
  • 舍入值来自另一个数据集。可能不是每个客户都有。
  • @Salih 如果不同行的舍入值不同,则它应该是数据框中的一列,而不是标量。

标签: python pandas dataframe rounding


【解决方案1】:

我相信您认为缺少值 - 然后将其替换为 0 或带有 if-else 语句的另一个标量:

rounding = np.nan

rounding = 0 if rounding != rounding else rounding
print (rounding)
0

或者:

rounding = 0 if pd.isna(rounding) else rounding
print (rounding)
0

如果存在值(不是缺失值):

rounding = 0.25

rounding = 0 if rounding != rounding else rounding
print (rounding)
0.25

df['A']=round(df['A'] - rounding + 0.5)
df['B']=round(df['B'] - rounding + 0.5)
print (df)
     A     B
0  1.0   1.0
1  1.0   4.0
2  2.0   5.0
3  1.0   6.0
4  5.0  10.0

【讨论】:

    【解决方案2】:

    一旦您的dataframe 中有一个列,每个观察值都带有“舍入”(您应该通过合并来自另一个dataframe 的数据来实现该列),您可以简单地执行以下操作:

    df['A'] = (df['A'] - df['rounding'].fillna(0.5) + 0.5).round(0)
    df['B'] = (df['B'] - df['rounding'].fillna(0.5) + 0.5).round(0)
    

    【讨论】:

      猜你喜欢
      • 2018-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      相关资源
      最近更新 更多