Ad
Create Column From Another Dataframe With Condition
I want to assign the labels in the df1 to df2 depending of df1['MinNum'] and df1['MaxMum']
df1
Label MinNum MaxNum
0 Rivière 0 0
1 Sols minéraux bruts 1 2
2 Sols peu évolués lithiques 3 4
df2
SOIL_ID
0 0.0
1 1.0
2 2.0
4 4.0
The condition is:
if df1['MinNum'] <= df2['SOIL_ID'] <= df1['MaxNum'] assign df1['Label'] to new label column for df2
I want to have this
SOIL_ID label
0 0.0 Rivière
1 1.0 Sols minéraux bruts
2 2.0 Sols minéraux bruts
4 4.0 Sols peu évolués lithiques
Ad
Answer
Probably not the most efficient way but I would create an intermediate DataFrame because df1
is not very easy to use.
df3 = pd.DataFrame(columns=["Sol_ID", "label"])
for i, row in df1.iterrows():
for j in range(row["MinNum"], row["MaxNum"]+1):
df3 = df3.append({"Sol_ID": j, "label": row["label"]}, ignore_index=True)
Which gives you a proper indexing:
Sol_ID label
0 0 Rivière
1 1 Sols minéraux purs
2 2 Sols minéraux purs
3 3 Sols peu évolués lithiques
4 4 Sols peu évolués lithiques
Then you can merge the 2 DataFrames:
df2.merge(df3, on="Sol_ID")
OUTPUT:
Sol_ID label
0 0 Rivière
1 1 Sols minéraux purs
2 2 Sols minéraux purs
3 4 Sols peu évolués lithiques
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad