I want to check if a given string is in a df and give the value of another column in this row into a different dataframe. I tried something like this:
df2['value']=np.where(df1['one'].str.contains(string),df1['two'],)
string = 'ef'
df1 :
| one | two |
| :--- | -----: |
| abc | hello |
| def | there |
In the end column ['value'] of Dataframe shall contain the string 'there'.
df2 :
| key | value |
| :--- | -----: |
| ef | there |
| ef | there |
CodePudding user response:
sring = 'ef'
df1['value'] = np.where(df1['one'].str.contains(string), df1['two'], df1['one'])
df1
one two value
1 abc hello abc
2 def there there
CodePudding user response:
You can achieve this by using pandas' mask
method:
df2 = (
df1.assign(
value=lambda df: df["one"].mask(df["one"].str.contains(string), df["two"])
)
.rename(columns={"two": "key"})
.drop("one", axis=1)
)
Output:
key value
0 hello abc
1 there there