【问题标题】:How to convert panda column to int while it has NULL values?如何在熊猫列具有 NULL 值时将其转换为 int?
【发布时间】:2019-11-02 01:44:45
【问题描述】:

所以我正在处理我的 CSV 文件,它在每个句子之后都有一个空白单元格“”,如下图所示。

当我使用以下方式打印列类型时:

print(data.dtypes)

我知道它们都是对象,但是我希望列 word_id、head_pred_id、sent_id 和 run_id 为 int64。

当我使用以下方法转换列数据类型时:

data.word_id = data.word_id.astype(int)

我收到一个错误:int() 以 10 为底的无效文字:' '

所以我认为空白单元格造成了问题,所以我将 CSV 文件本身中的它们替换为 NULL。

现在 4 列类型自动设置为“Float64”,但是当我对它们执行某些操作时,我得到了同样的错误: ValueError: int() 以 10 为底的无效文字:''

我仔细检查了是否有遗漏的单元格,但我没有遗漏任何空白单元格在我的 CSV 文件中都设置为 NULL。

下面是出现错误的sn-p代码:

def encode_inputs(sents):
        """
        Given a dataframe which is already split to sentences,
        encode inputs for rnn classification.
        Should return a dictionary of sequences of sample of length maxlen.
        """
        word_inputs = []
        pred_inputs = []
        pos_inputs = []


        assert(all([len(set(sent.run_id.values)) == 1
                    for sent in sents]))


        run_id_to_pred = dict([(int(sent.run_id.values[0]),
                                get_head_pred_word(sent))
                               for sent in sents]) ***ERROR HERE****

这是发送到上述函数的变量“sents”


def get_sents_from_df( df):

      #Split a data frame by rows accroding to the sentences
      return [df[df.run_id == run_id]
            for run_id
            in sorted(set(df.run_id.values))]

【问题讨论】:

    标签: python excel pandas csv


    【解决方案1】:

    首先将非数字值(如空字符串)转换为NaNs,然后如果使用pandas 0.24+,则可以将列转换为integers

    data.word_id = pd.to_numeric(data.word_id, errors='coerce').astype('Int64')
    

    【讨论】:

    • 非常感谢它的工作,它们现在是整数,但我收到错误 IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (@987654326 @) 和整数或布尔数组是有效的索引,知道为什么吗?
    • @ElenaGT - 很难知道,数据是否保密?
    【解决方案2】:

    pd.numeric() 函数中有一个强制属性
    data['word_id']= pd.to_numeric(data['word_id'], errors='coerce').astype(int)

    如果是多列
    1.创建列列表
    col =['word_id','head_pred_id']
    df[col] = df[col].apply(lambda x :pd.to_numeric(x,errors='coerce').astype(int),axis=0)

    【讨论】:

    • 不先将空字符串替换为Null,问题中提到字符串替换为NULL
    • 很抱歉我已经编辑了解决方案。@ElenaGT 感谢您的纠正
    • 非常感谢它的工作,它们现在是整数,但我收到错误 IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer或布尔数组是有效的索引,知道为什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 2017-01-03
    • 2016-03-09
    • 2020-07-28
    • 1970-01-01
    • 2019-02-14
    • 2021-05-10
    相关资源
    最近更新 更多