Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use values from a Pandas data frame in a calcul?

I have a Pandas data frame. In the A columns there are ints like [1, 5, 3], and in the B columns there are string like ["abcdef", "ghijklmno", "qwertyuiop"]

I want to create a C columns with the columns B first char according to the culumns A. In my example I want the C columns to be like ["a", "ghijk", "qwe" ]

I tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

data_frame['C'] = data_frame.B.str[:data_frame["A"]]

But it doesn’t work.

>Solution :

You can set use a lambda function and set the axis = 1 to use column A to set the string length of B

df = pd.DataFrame({
    'A' : [1, 5, 3,],
    'B' : ["abcdef", "ghijklmno", "qwertyuiop"]
})
df['c'] = df.apply(lambda x : x['B'][:x['A']], axis = 1)
df
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading