嗨,我有一個包含多個家庭的資料集,其中家庭中的所有人都在兩個資料源之間進行了匹配。因此,資料框由一個“家庭”列和兩個人列(每個資料源一個)組成。然而,有些人(如下面的 Jonathan 或 Peter)無法匹配,因此有一個空白的第二人稱欄。
| 家庭 | Person_source_A | Person_source_B |
|---|---|---|
| 1 | 奧利弗 | 奧利弗 |
| 1 | 喬納森 | |
| 1 | 艾米 | 艾米 |
| 2 | 大衛 | 戴夫 |
| 2 | 瑪麗 | 瑪麗 |
| 3 | 莉齊 | 伊麗莎白 |
| 3 | 彼得 |
由于資料框很大,我的目標是對不匹配的個人進行抽樣,然后輸出一個包含家庭中所有人的 df,其中只有抽樣的不匹配的人存在。即說我的隨機樣本包括 Oliver 但不包括 Peter,那么我將只輸出家庭 1。
我的問題是我已經過濾了樣本,現在我一直在進步。join、agg/groupBy... 的一些組合會起作用,但我很掙扎。我在采樣的不匹配名稱中添加了一個標志來識別它們,我認為這很有幫助......
我的代碼:
# filter to unmatched people
df_unmatched = df.filter(col('per_A').isNotNull()) & col('per_B').isNull())
# take random sample of 10%
df_unmatched_sample = df_unmatched.sample(0.1)
# add flag of sampled unmatched persons
df_unmatched_sample = df_unmatched.withColumn('sample_flag', lit('1'))
uj5u.com熱心網友回復:
因為它與您的意圖有關:
我只想減少我的資料框以僅顯示存在不匹配人員的家庭的完整家庭,該人員是從所有不匹配的人中隨機抽取的
使用您現有的方法,您可以Household對示例記錄使用連接
# filter to unmatched people
df_unmatched = df.filter(col('per_A').isNotNull()) & col('per_B').isNull())
# take random sample of 10%
df_unmatched_sample = df_unmatched.sample(0.1).select("Household").distinct()
desired_df = df.join(df_unmatched_sample,["Household"],"inner")
編輯 1
回應op的評論:
是否有一種稍微不同的方式來保留一個標志來識別抽樣的未匹配人員(因為有些家庭有不止一個未匹配人員)?
將標志列添加到您的樣本后,對現有資料集進行左連接可能會幫助您實作這一目標,例如:
# filter to unmatched people
df_unmatched = df.filter(col('per_A').isNotNull()) & col('per_B').isNull())
# take random sample of 10%
df_unmatched_sample = df_unmatched.sample(0.1).withColumn('sample_flag', lit('1'))
desired_df = (
df.alias("dfo").join(
df_unmatched_sample.alias("dfu"),
[
col("dfo.Household")==col("dfu.Household") ,
col("dfo.per_A")==col("dfu.per_A"),
col("dfo.per_B").isNull()
],
"left"
)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/374322.html
