I have a pandas dataframe with four columns: ['Source', 'Target', 'Type', 'Weight']
The combination of 'Source' and 'Weight' is basically the key for the dataframe, so at most one combination of 'Source' and 'Weight' is possible.
Now I want to check, whether a certain row is already in the dataframe, if so, access it (by adding 1 to Weight) and if not, create it.
How can I search for two conditions, access if there is a match and create a new row if not?
if(df[(df.Source == source) & (df.Target == target)].empty()):
df = df.append([source, target, 'bidirectional', 1])
else:
df[(df.Source == source) & (df.Target == target)].Weight = 1
CodePudding user response:
It would be rather following function:
def add(df, source, target):
if df[(df.Source == source) & (df.Target == target)].empty:
df.loc[max(df.index) 1] = [source, target, 'bidirectional', 1]
else:
df.loc[(df.Source == source) & (df.Target == target), "Weight"] = 1
