【问题标题】:Convert column of lists to integer将列表列转换为整数
【发布时间】:2021-11-30 03:56:41
【问题描述】:

尝试在编码后转换为整数,但它们是对象,所以我首先将它们转换为字符串

train_df["labels"] = train_df["labels"].astype(str).astype(int)

我收到了这个错误

以 10 为基数的 int() 的无效文字:'[0, 1, 0, 0]

数据集中的一行示例是

text                        labels
[word1,word2,word3,word4]    [1,0,1,0]

【问题讨论】:

    标签: python pandas dataframe bert-language-model


    【解决方案1】:

    因为train_df["labels"].astype(str)之后,这个Series变成了Series of lists,所以不能将list转换成type int

    如果train_df["labels"] 中的每个元素都是list 类型,你可以这样做:

    train_df["labels"].apply(lambda x: [int(el) for el in x])
    

    如果是str类型,你可以这样做:

    train_df["labels"].apply(lambda x: [int(el) for el in x.strip("[]").split(",")])
    

    您大概想训练一些模型,但您不能使用 pd.Series 列表来完成它。您需要将其转换为 DataFrame。如果不查看超过 1 行数据,我无法说出如何做到这一点。

    【讨论】:

      【解决方案2】:

      从外观上看,您的问题是因为表示为字符串的数字可能是浮点数。如果这是问题,那么下面应该解决它:

      train_df["labels"] = train_df["labels"].astype(str).astype(float).astype(int)
      

      (在 Python 中,您不能将浮点数的字符串表示形式转换为 int 类型。)

      从错误中,我怀疑您的字符串实际上包含括号和逗号(从问题中并不清楚)。如果是这种情况,您需要告诉 Python 如何处理它们。例如,如果 train_df["labels"] 等于 "[1,0,1,0]" 那么你可以在下面使用:

      train_df_labels = [int(label) for label in train_df["labels"][1:-1].split(',').strip()]
      
      #first getting rid of the brackets in the string, 
      #then splitting the string at commas and getting rid of the spaces,
      #finally, converting values to int type one by one and making a list out of them
      

      【讨论】:

      • 变成浮点数产生错误 ValueError: could not convert string to float: '[0, 1, 0, 0]'
      • 看来你的字符串甚至包括括号和逗号,是这样吗?如果是,那么 Python 当然不能靠自己解决所有这些问题。你应该这样做(我也将它添加到我的答案中): train_df_labels = [int(label) for label in train_df["labels"][1:-1].split(',')]
      猜你喜欢
      • 2020-01-23
      • 2016-02-04
      • 2016-12-16
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 2010-10-21
      相关资源
      最近更新 更多