I have to edit all cells of one column (here column named "Links") in Pandas DataFrame conditionally using original value of each cell.
I know how to modify each cell of column, but don't know how to edit cell using original value of cell and make modification conditionally.
I have simple sample of Data Frame:
I am interested in last column "Links".
If cell endwswith .html I need to change it to:
<A> <original value> </A>
for example:
/l/sf-49ers/456346aaa.html
if it is number I need to make:
some-domain.info/number
for example:
some-domain.info/343
If it is text (string):
I need to put it in B tags:
for example:
"Baltimore Rayens"
If it is None I need to replace it with text "No link specified".
I have used this syntax:
def change_links(df):
conditions = (..........)
values = [.......................]
df['Links'] = np.select(conditions, values)
return df
but this does not work for me.
CodePudding user response:
As I understand you correct, you need to use apply function:
def change_links(link):
if 'html' in link:
newLink=0 #here change your link
elif link[-1].isdigit():
newLink='some-domain.info/' str(link) #or do what you nedd
else:
newLink=1 #here add your tags
return newLink
df['newLink'] = df['Links'].apply(lambda x(change_links(x)))
CodePudding user response:
Theres a formatting probleme in your question, but you can achieve what you want with the function apply()
def myFunction(value):
# For example for a int
new_value = "some-domain.info/" str(value)
return new_value
df['Links'] = df.['Links'].apply(myFunction)
I could complete the answer with more information.
CodePudding user response:
Since your question is kinda messy, I am answering your question based on what I have understood. You have two options in front of you:
apply
map
in either cases you simply need to do something like what follows:
def myCustomFunc(valueOfRow):
# you need to change the value inside this function.
return valueOfRow "/more-link"
df["Link"] = df["Link"].apply(myCustomFunc)
If you are interested in map, you can use map
function instead of apply
in the abovementioned cell.