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 can I create a list of range of numbers as a column of dataframe?

  • Thread starter Thread starter AmirX
  • Start date Start date
A

AmirX

Guest
My DataFrame is:

Code:
import pandas as pd

df = pd.DataFrame(
        {
           'a': [20, 100],
           'b': [2, 3],
           'dir': ['long', 'short']
        }
 )

Expected output: Creating column x:

Code:
     a  b    dir    x
0   20  2   long    [22, 24, 26]
1  100  3  short    [97, 94, 91]

Steps:

x is a list with length of 3. a is starting point of x and b is step that a increases/decreases depending on dir. If df.dir == long x ascends otherwise it descends.

My Attempt based on this answer:

Code:
df['x'] = np.arange(0, 3) * df.b + df.a

Which does not produce the expected output.
<p>My DataFrame is:</p>
<pre><code>import pandas as pd

df = pd.DataFrame(
{
'a': [20, 100],
'b': [2, 3],
'dir': ['long', 'short']
}
)
</code></pre>
<p>Expected output: Creating column <code>x</code>:</p>
<pre><code> a b dir x
0 20 2 long [22, 24, 26]
1 100 3 short [97, 94, 91]
</code></pre>
<p>Steps:</p>
<p><code>x</code> is a list with length of 3. <code>a</code> is starting point of <code>x</code> and <code>b</code> is step that <code>a</code> increases/decreases depending on <code>dir</code>. If <code>df.dir == long</code> <code>x</code> ascends otherwise it descends.</p>
<p>My Attempt based on this <a href="https://stackoverflow.com/a/45233237/10200497">answer</a>:</p>
<pre><code>df['x'] = np.arange(0, 3) * df.b + df.a
</code></pre>
<p>Which does not produce the expected output.</p>
 

Latest posts

J
Replies
0
Views
1
Jeff P Chacko
J
Top