【问题标题】:python pandas get first digits of column valuespython pandas获取列值的前几位
【发布时间】:2019-11-15 14:28:47
【问题描述】:

我需要为 daframe 的每一行获取存储在另一个索引(或 reset_index() 之后的列)中的数字的前两位。我该怎么做?

我的数据框:

        value
index1       
110202      1
223168      5
850484      2
298008      3
950000      6
113500      6
849464      2
849616     10

我想获得即:

                  value
index1 new_value       
110202 11             1
223168 22             5
850484 85             2
298008 29             3
950000 95             6
113500 11             6
849464 84             2
849616 84            10

【问题讨论】:

    标签: python pandas indexing digits


    【解决方案1】:

    假设index1df 的索引,你可以这样做:

    df['new_value'] = df.index.astype(str).str[:2]
    print(df)
    

    输出

            value new_value
    index1                 
    110202      1        11
    223168      5        22
    850484      2        85
    298008      3        29
    950000      6        95
    113500      6        11
    849464      2        84
    849616     10        84
    

    基本上将列转换为字符串列,然后使用str 访问器获取前两个字符。有关处理文本数据的更多信息,请参阅here

    您也可以重置索引并访问index1 列,例如:

    df = df.reset_index()
    df['new_value'] = df['index1'].astype(str).str[:2]
    print(df.set_index(['index1', 'new_value']))
    

    输出

                      value
    index1 new_value       
    110202 11             1
    223168 22             5
    850484 85             2
    298008 29             3
    950000 95             6
    113500 11             6
    849464 84             2
    849616 84            10
    

    请注意,在此替代解决方案中,我将索引设置为列 new_valueindex1

    【讨论】:

    • 谢谢,但我收到此错误:TypeError: Setting dtype to any other than object is not supported
    • @user9187374 更新了答案,如果替代方案有效,请告诉我。
    【解决方案2】:

    使用 df.index.values 从索引中创建一个列表 然后遍历该数组中的值并获取前 2 个字符

    【讨论】:

      猜你喜欢
      • 2022-11-02
      • 1970-01-01
      • 2022-01-17
      • 2015-05-12
      • 1970-01-01
      • 2017-09-29
      • 1970-01-01
      • 1970-01-01
      • 2017-02-22
      相关资源
      最近更新 更多