[英]Create a new column using a condition from other two columns in a dataframe
[英]How to create new column in dataframe based on condition from other dataframe?
df1 = pd.DataFrame({"DEPTH":[0.5, 1, 1.5, 2, 2.5],
"POROSITY":[10, 22, 15, 30, 20],
"WELL":"well 1"})
df2 = pd.DataFrame({"Well":"well 1",
"Marker":["Fm 1","Fm 2"],
"Depth":[0.7, 1.7]})
大家好。 我有兩個數據框,我想在 df1 上創建一個新列,例如:df1["FORMATIONS"],其中包含基於 df2["Depth"] 和 df1[ 深度限制的 df2["Marker"] 值的信息“深度”]。
因此,例如,如果 df2["Depth"] = 1.7,則 df1["DEPTH"] > 1.7 的 df1 中的所有樣本都應在此新列 df1["FORMATIONS"] 中標記為“Fm 2”。
最終的 dataframe df1 應該如下所示:
DEPTH POROSITY WELL FORMATIONS
0.5 10 well 1 nan
1 22 well 1 Fm 1
1.5 15 well 1 Fm 1
2 30 well 1 Fm 2
2.5 20 well 1 Fm 2
任何人都可以幫助我嗎?
您在這里所做的是將連續數據轉換為分類數據。 使用pandas
有很多方法可以做到這一點,但其中一種更廣為人知的方法是使用pandas.cut
。
指定bins
參數時,需要將float(inf)
添加到列表末尾,以表示最后一個 bin 趨於無窮大。
df1["FORMATIONS"] = pd.cut(df1.DEPTH, list(df2.Depth) + [float('inf')], labels=df2.Marker)
df1
現在將是:
注意。 用於合並的列需要先排序
pd.merge_asof(df1,
df2[['Marker', 'Depth']].rename(columns={'Marker': 'Formations'}),
left_on='DEPTH', right_on='Depth')
output:
DEPTH POROSITY WELL Formations Depth
0 0.5 10 well 1 NaN NaN
1 1.0 22 well 1 Fm 1 0.7
2 1.5 15 well 1 Fm 1 0.7
3 2.0 30 well 1 Fm 2 1.7
4 2.5 20 well 1 Fm 2 1.7
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.