[Python] creating a new column in polars applying a function to a column

Discussão em 'Python' iniciado por Stack, Março 13, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following code for manipulating a polars dataframe that does not work

    import polars as pl
    import xml.etree.ElementTree as ET

    # create a sample dataframe
    df = pl.DataFrame({
    'A': [1, 2, 3],
    'B': ['<p>some text</p><p>bla</p>', '<p>some text<p><p>foo</p>', '<p>some text<p>']
    })

    def func(mystring):
    return mystring*2

    def func2(xml_string):
    root = ET.fromstring(xml_string)
    text_list = []
    for elem in root.iter():
    text = elem.text.strip() if elem.text else ''
    text_list.append(text)
    return test_list

    # create a sample series to add as a new column
    df = df.with_columns((pl.col("A").map_batches(lambda x: func(x)).alias('new_col')))
    df = df.with_columns((pl.col("B").map_batches(lambda x: func2(x)).alias('new_col2')))

    print(df)


    The first line for adding a column works, i.e. adding new_col

    but the second one does not work.

    The error that I get is:


    ComputeError: TypeError: a bytes-like object is required, not 'Series'
    ​

    Basically the use case that I have iss that a column contains XML string that I have to manipulate creating a XML object and extracting information.

    How can I proceed?

    Continue reading...

Compartilhe esta Página