【问题标题】:change number negative sign position更改数字负号位置
【发布时间】:2022-08-17 23:52:14
【问题描述】:

您好,我有以下 df 示例

 col1      col2
 12.4      12.32
 11.4-     2.3
 2.0-      1.1

我需要负号在数字的开头而不是结尾

 col1      col2
 12.4      12.32
 -11.4     2.3
 -2.0      1.1

我正在尝试使用以下功能,到目前为止,我可以获取带有符号的数据并正确打印它们,但我不再知道如何在我的列中替换它们

updated_data = \'\' # iterate over the content
for line in df[\"col1\"]:
# removing last word
    updated_line = \' \'.join(str(line).split(\'-\')[:-1])
    print(updated_line)

请问你能帮帮我吗?或者如果有更简单的方法,我将不胜感激

    标签: python dataframe sign negative-number


    【解决方案1】:
    df['col1']=np.where(df['col1'].str.contains('-'),
             df['col1'].str.replace(r'-','',regex=True).astype('float')*(-1),
             df['col1']
            )
    df
    
    col1    col2
    0   12.4    12.32
    1   -11.4   2.30
    2   -2.0    1.10
    

    【讨论】:

      猜你喜欢
      • 2015-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多