What am I doing wrong with this syntax of multiple if – else in apply pandas?

Advertisements I am trying to execute this code: data[‘lga_code’] = data.loc[:,’lga’].apply(lambda x: ‘Rural’ if x == endswith(‘Rural’) (‘Urban’ if x == endswith(‘Urban’) else ‘other’)) But I get this error: SyntaxError: invalid syntax. What is wrong? The data is a dataframe that it has 125 categories. I want to group them all into three, and that’s… Read More What am I doing wrong with this syntax of multiple if – else in apply pandas?

Search of a set of strings in a column containing strings in a pandas dataframe

Advertisements I have a df with multiple columns, one of which is a string with many words(text column). I also have a set of words, S, that I need to look for. I want to extract the rows of the df that contain at least one word from S in its text column df_filtered=df[df[‘text’].str.contains(‘word’)] This… Read More Search of a set of strings in a column containing strings in a pandas dataframe

pandas dataframe column string parsing

Advertisements I have a DF in which one of the columns has strings of the form 0 word1|category1 word2|category2 1 word3|category3 word4|category4 word2|category2 .. 2 word1|category1 word4|category4 word3|category3 .. where "word1|category1 word4|category4 word3|category3 .." is a string I need an output dictionary mapping that maps unique set of words to their respective categories. I tried… Read More pandas dataframe column string parsing

Reformat/pivot pandas dataframe

Advertisements For each row, I want that rows’ index to be changed to column_index, and have the whole thing split from x row * y columns to 1 row * x*y columns shape. import pandas as pd df = pd.DataFrame(data=[[‘Jon’, 21, 1.77,160],[‘Jane’,44,1.6,130]],columns=[‘name’,’age’, ‘height’,’weight’]) want = pd.DataFrame(data=[[‘Jon’, 21, 1.77,160,’Jane’,44,1.6,130]],columns=[‘name_0′,’age_0’, ‘height_0′,’weight_0′,’name_1′,’age_1’, ‘height_1′,’weight_1’]) # original df name age… Read More Reformat/pivot pandas dataframe

Python Dataframes: How can I apply a function to value x and y, where x is in df1 and y is in df2?

Advertisements I have been struggling to find a nice solution to this problem: I have a 100-rows-dataframe df1 , Col 0, Col 1, Col 2, Score, Combined … 23 Oslo, isCapitalOf, Norway, 0.9, None … I also have another 100-rows-dataframe df2 , Col 0, Col 1, Col 2, Score, Combined … 43 Norway, highestMountain, Galdhøpiggen,… Read More Python Dataframes: How can I apply a function to value x and y, where x is in df1 and y is in df2?