OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

How to create a new column within a polars DataFrame that is equal to a list?

  • Thread starter Thread starter Datawiz
  • Start date Start date
D

Datawiz

Guest
I am currently trying to create a new column within a polars dataframe (df). Within my df, there are many many rows, and within this new column I only want my existing list to populate wherever certain conditions are met.

I know that in pandas, I could do something like the following (where 'output' is my new column and assuming list is the same length as the filtered df) :

Code:
df = pd.DataFrame({
    'cond1': [-1, 0, 1, 2, 2, 3, 4, 5],
    'cond2': ['No', 'No', 'No', 'Yes','Yes', 'Yes', 'Yes', 'Yes']
})
conditions = ((df['cond1']>=1) & (df['cond2'] == 'Yes'))
list_new = [1,2,3,4,5]

df.loc[conditions, 'output'] = list_new

How would I do this same thing but within polars? I want the total number of rows to stay the same, I just want to update the new column wherever the conditions are met

I tried a few variations of the following but nothing has seemed to work:

Code:
df_polars = df_polars.with_columns(pl.when(conditions).then(list_new).alias('output')
<p>I am currently trying to create a new column within a polars dataframe (df). Within my df, there are many many rows, and within this new column I only want my existing list to populate wherever certain conditions are met.</p>
<p>I know that in pandas, I could do something like the following (where 'output' is my new column and assuming list is the same length as the filtered df) :</p>
<pre><code>df = pd.DataFrame({
'cond1': [-1, 0, 1, 2, 2, 3, 4, 5],
'cond2': ['No', 'No', 'No', 'Yes','Yes', 'Yes', 'Yes', 'Yes']
})
conditions = ((df['cond1']>=1) & (df['cond2'] == 'Yes'))
list_new = [1,2,3,4,5]

df.loc[conditions, 'output'] = list_new
</code></pre>
<p>How would I do this same thing but within polars? I want the total number of rows to stay the same, I just want to update the new column wherever the conditions are met</p>
<p>I tried a few variations of the following but nothing has seemed to work:</p>
<pre><code>df_polars = df_polars.with_columns(pl.when(conditions).then(list_new).alias('output')
</code></pre>
 

Latest posts

I
Replies
0
Views
1
impact christian
I
Top