Python Forum

Full Version: How to add columns to polars dataframe
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am using polars to read an xlsx sheet in a dataframe.

How can I add columns to the start of the worksheet? Since using using "with_colums" add columns to the datafram but these are added to the of the sheet
Well, can you try the below code I hope you can get the result you are looking for.

Quote:import polars as pl

# Create a sample DataFrame
data = {
"A": [1, 2, 3],
"B": [4, 5, 6]
}

df = pl.DataFrame(data)

# Create new columns
new_columns = {
"X": [7, 8, 9],
"Y": [10, 11, 12]
}

# Insert the new columns at the start of the DataFrame
index_to_insert = 0 # Insert at the start
df = df.insert_at_idx(index_to_insert, new_columns)

# Print the updated DataFrame
print(df)
Thanks