【问题标题】:Problem in elemintaing the brackets () and post processing the dataframe using Pandas in Python在 Python 中使用 Pandas 删除括号 () 和后处理数据帧的问题
【发布时间】:2021-01-15 13:31:03
【问题描述】:

我只是Python的初学者,所以请原谅这个问题,我尝试了很多来完成它,但失败了,因此我发布了这个。我有一个数据集,如下所示:

  5.96303e-07             (11.6667 3.21427 -2.20471e-07)             (11.8746 -1.75419 -2.37923e-07)             (8.66991 -2.84873 5.29442e-07)             (2.19427 13.547 1.16203e-05)
  9.67139e-07             (11.6171 3.16081 -8.83286e-08)             (11.8851 -1.763 -4.38136e-07)             (8.68988 -2.85339 1.81039e-07)             (1.61058 13.629 4.42662e-07)
  1.34613e-06             (11.5562 3.11037 -7.74061e-08)             (11.8897 -1.77006 -3.81523e-07)             (8.70652 -2.8608 8.00436e-08)             (1.47268 13.5569 -2.03173e-06)
  1.73261e-06             (11.4961 3.06921 -1.49294e-07)             (11.8919 -1.77567 -3.48887e-07)             (8.71974 -2.86802 5.2652e-08)             (1.59798 13.4556 -2.52073e-06)
  2.12563e-06             (11.4423 3.03706 -1.53771e-07)             (11.8932 -1.78022 -3.33928e-07)             (8.73 -2.87398 4.65075e-08)             (1.77817 13.3679 -2.42045e-06)

现在,当我访问实例 df.iloc[:,1] 的数据框时,它给了我(11.6171,当我尝试绘制它时——它给了我错误,然后我认为由于 "(" 正在创建一个问题,我使用df.replace('\(','',regex=True).replace('\)','',regex=True) 删除了它。绘图功能似乎有效,但给出了非常奇怪的数字(不允许发布数字)。除此之外,当我尝试像(df.iloc[:,1])^2 这样进行一些计算时,它给了我错误,上面写着:

TypeError: can't multiply sequence by non-int of type 'str' 

我猜数据的格式不正确。任何意见或建议都会有很大帮助。提前致谢。

【问题讨论】:

    标签: python pandas dataframe matplotlib


    【解决方案1】:

    有两个相对较小的问题。类似以下的内容可能是您正在寻找的内容。也许吧。

    首先,您要绘制的列是一个字符串。本质上它包含字母/符号。即使您删除了“(”“)”,“数字”仍然被视为字符串。

    # To convert a "3.14" (string) to a 3.14 (float) 
    # floats are basically decimals
    my_string = "3.14"
    my_number = float(my_string)
    

    此外,字符串中有多个“数字”。因此,要绘制该列中的数字,我认为您首先需要拆分字符串然后转换为数字。

    # Use your code to replace the special characters
    df.replace('\(','',regex=True).replace('\)','',regex=True)
    
    # new data frame with split value columns 
    new = df["colname_with_three_numbers"].str.split(" ", n = 2, expand = True) 
    
    # Making separate first name column from new data frame 
    df["first_number"]= new[0]  
    df["second_number"]= new[1] 
    df["third_number"]= new[2]
    
    # change the type to allow you to plot something like this should work
    df["first_number"] = float(df["first_number"])
    
    df
    

    【讨论】:

    • 非常感谢,我会尝试、实施并恢复。
    • 希望对您有所帮助。祝你好运! :)
    【解决方案2】:

    这是解决这个问题的一个非常糟糕的方法,但如果数据集不是太大,您可以使用 for 循环获取每个元素并使用 str.replace(")","") 删除括号。

    【讨论】:

    • 是的,有道理,可能在那个方向上,我猜使用“awk”会起作用吗?谢谢:)
    猜你喜欢
    • 2014-01-20
    • 2017-02-17
    • 2022-11-16
    • 1970-01-01
    • 2022-12-23
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 2016-08-18
    相关资源
    最近更新 更多