【问题标题】:How do I split by "/" delimiters using index in python?如何在 python 中使用索引按“/”分隔符分割?
【发布时间】:2019-02-27 21:20:22
【问题描述】:

在一个 DataFrame 中,一些列在 DataFrame 中。我想使用索引将列值按“/”分割。下面是我要拆分数据的列列表。

Eg:- split_columns = ['Fuel', 'Air Pollution Score', 'City MPG', 'Hwy MPG', 'Cmb MPG', 'Greenhouse Gas Score']

如果在 Fuel 中包含数据,则输出应类似于“乙醇/气体”。

这是我的代码-

split_columns = ['Fuel', 'Air Pollution Score', 'City MPG', 'Hwy MPG', 'Cmb MPG', 'Greenhouse Gas Score']

for c in split_columns:
  df1[c] = df1[c].apply(lambda x: x.split("/")[0])
  df2[c] = df2[c].apply(lambda x: x.split("/")[1])

当我执行上面的代码时,我发现一个错误“索引超出范围”。

【问题讨论】:

    标签: python pandas numpy indexoutofboundsexception delimiter


    【解决方案1】:

    它有一个索引问题: 我找到了2个解决方案: 1)我把它分成2个(在Jupyter的2个单元中),这个错误就消失了。

    对于 split_columns 中的 c: df1[c] = df1[c].apply(lambda x: x.split("/")[0]) 对于 split_columns 中的 c: df2[c] = df2[c].apply(lambda x: x.split("/")[1])

    2) 我重命名了第二个索引 对于 split_columns 中的 c: df1[c] = df1[c].apply(lambda x: x.split("/")[0]) df2[c] = df2[c].apply(lambda x: x.split("/")[0])

    【讨论】:

      【解决方案2】:

      我建议将Series.str.split 与索引str[0]str[1] 一起用于选择第一个和第二个嵌套列表。

      如果/ 不存在,则输出为NaN 值,而不是IndexOutOfBoundsException

      for c in split_columns:
        df1[c] = df1[c].astype(str).str.split("/").str[0]
        df2[c] = df2[c].astype(str).str.split("/").str[1]
      

      【讨论】:

      • 收到此错误Can only use .str accessor with string values, which use np.object_ dtype in pandas
      • @user8487380 - 添加.astype(str)
      • @user8487380 -split_columns的所有列都用字符串填充?
      【解决方案3】:

      这里只是意味着有时在其他几列中没有"/"。因此,当没有"/" 时, split 将只有一个元素。但是,您正在访问x.split("/")[1]。这导致索引错误。要解决此问题,只需检查 x 中是否存在 "/" 或仅检查拆分的长度。如果大于 1,则表示存在 "/"

      【讨论】:

      • 如何查看分割长度。我们将获取每个混合行并将它们分成两个新行 - 一个具有第一种燃料类型的值(“/”之前的值),另一个具有第二种燃料类型的值(“/”之后的值")。
      • 分割长度不过是len(x.split("/"))
      猜你喜欢
      • 2016-02-15
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 2013-11-24
      • 2017-03-25
      • 2015-07-06
      相关资源
      最近更新 更多