Question:
Creating a list in a dataframe column from two other columns' values

Summary:

You can create a list of a range of numbers as a column in a DataFrame using the popular Python library called Pandas. 

In this example:


  • start_number: the starting number of the range.

  • end_number: the ending number of the range.

  • step: the step size between numbers in the range.

The range function is used to generate a sequence of numbers, and then you can pass this sequence as a column to the DataFrame constructor.


Replace 'Column_Name' with the desired name for your column. Adjust the start_number, end_number, and step variables according to your requirements.


Solution:

Sample code:

import pandas as pd


# Define the range of numbers

start_number = 1

end_number = 10

step = 1


# Create a DataFrame with a column of the range of numbers

df = pd.DataFrame({'Column_Name': range(start_number, end_number + 1, step)})


# Display the DataFrame

print(df)


Working code after DataFrame.apply on rows.

# create 1 for long, else -1

d = np.where(df['dir'].eq('long'), 1, -1)[:,None]


# convert a and b to numpy as a column vector

a = df['a'].to_numpy()[:,None]

b = df['b'].to_numpy()[:,None]


# combine

N = 3

x = np.arange(1, N+1)

df['x'] = list(a + d*b*x)


Output:

    a  b    dir             x

0   20  2   long  [22, 24, 26]

1  100  3  short  [97, 94, 91]


Credit:> Stack Overflow


Suggested blogs:

>How .transform handle the splitted groups?

>Can I use VS Code's launch config to run a specific python file?

>Python: How to implement plain text to HTML converter?

>How to write specific dictionary list for each cycle of loop?

>Reading a shapefile from Azure Blob Storage and Azure Databricks

>How to replace a value by another in certain columns of a 3d Numpy array?

>How to fix "segmentation fault" issue when using PyOpenGL on Mac?


Submit
0 Answers