【问题标题】:delete all characters after specific character, not character itself, in whole column, python删除特定字符后的所有字符,而不是字符本身,在整列中,python
【发布时间】:2021-09-13 15:18:42
【问题描述】:

我有一个数据框,为了重现性的目的,我把它做成了一个字典。我想删除“索引”列中最后一个“1”之后的所有字符,而不是删除“1”本身。有人知道如何快速做到这一点吗?我尝试了以下方法,但它也删除了“1”:

df1['index'] = [x.split('1')[-1] for x in df1['index']]
{0: {'1': 0.001549586776859504,
  '10': 0.001549586776859504,
  '11': 0.00017217630853994488,
  '12': 4.304407713498622e-05,
  '13': 0.00012913223140495865},
 1: {'1': 0.000387396694214876,
  '10': 0.000387396694214876,
  '11': nan,
  '12': nan,
  '13': nan},
 2: {'1': 0.001162190082644628,
  '10': 0.001162190082644628,
  '11': 9.838646202282564e-05,
  '12': 2.459661550570641e-05,
  '13': 7.378984651711923e-05},
 3: {'1': 0.015883264462809916,
  '10': 0.015883264462809916,
  '11': 0.0006149153876426602,
  '12': 0.00015372884691066505,
  '13': 0.0004611865407319952},
 4: {'1': 0.00387396694214876,
  '10': 0.00387396694214876,
  '11': 0.00012298307752853205,
  '12': 3.0745769382133014e-05,
  '13': 9.223730814639904e-05},
 5: {'1': 0.001549586776859504,
  '10': 0.001549586776859504,
  '11': nan,
  '12': nan,
  '13': nan},
 6: {'1': 0.005423553719008264,
  '10': 0.005423553719008264,
  '11': 0.0002951593860684769,
  '12': 7.378984651711923e-05,
  '13': 0.00022136953955135768},
 7: {'1': 0.001549586776859504,
  '10': 0.001549586776859504,
  '11': 0.00017217630853994488,
  '12': 4.304407713498622e-05,
  '13': 0.00012913223140495865},
 8: {'1': 0.001162190082644628,
  '10': 0.001162190082644628,
  '11': nan,
  '12': nan,
  '13': nan},
 9: {'1': 0.001549586776859504,
  '10': 0.001549586776859504,
  '11': 7.378984651711923e-05,
  '12': 1.8447461629279807e-05,
  '13': 5.534238488783942e-05},
 'index': {'1': '00', '10': '000', '11': '0', '12': '20', '13': '30'}}

【问题讨论】:

    标签: python string dataframe character


    【解决方案1】:

    此解决方案将 int 转换为字符串,然后从零开始搜索第一个数字不同的数字,然后获取您需要的分区(从开始到不同于零的数字的位置)并将其转换回浮点数。 快乐编码

    df1['index']=[float(x[:x.find(x.split(".")[-1].replace("0","")[0])+1]) for x in list(map(str,df1['index']))]
    

    【讨论】:

    • 谢谢。这将删除第一个 1 前面的 p ,我想删除字符串中最后一个 1 之后的所有内容
    • 试试这个新的解决方案
    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
    猜你喜欢
    • 1970-01-01
    • 2010-10-28
    • 2019-09-21
    • 2020-06-02
    • 1970-01-01
    • 2012-03-08
    • 2016-01-02
    相关资源
    最近更新 更多