Reputation:
I try to replace a character in some strings with conditions in a pandas dataframe column. The function works but the rows of the dataframe display None.
def char_replace(string):
if string.startswith(tuple(list)):
return string.replace("_", "-", 1)
df["col1"] = df["col1"].apply(char_replace)
Upvotes: 2
Views: 780
Reputation: 837
You don't even need an else statement. If the condition is not met, the function will proceed to the second return statement.
def char_replace(string):
if string.startswith(tuple(list)):
return string.replace("_", "-", 1)
return string
df["col1"] = df["col1"].apply(char_replace)
Upvotes: 1
Reputation: 82
def char_replace(string):
if string.startswith(tuple(list)):
return string.replace("_", "-", 1)
else:
return string
df["col1"] = df["col1"].apply(char_replace)
need to have an option if string does not start with that paticular value
Upvotes: 0