![](/img/trans.png)
[英]Pandas: find all unique values in one column and normalize all values in another column to their last value
[英]Excel If one column contains unique values, and another column contains one true value, return all true values for those unique values
我在 Exel(365 版本)中有一個超過 78K 行的大文件。 我正在嘗試編寫一個公式,該公式將返回一個True
或False
值,該值取決於Column A
中的唯一值(21K 唯一值),並且如果Column B
中的任何值是True
,那么Column C
應該返回一個True
值Column A
中的唯一值范圍。
例如,我有以下數據:
Column A Column B
1 True
1 False
1 False
2 False
2 False
3 False
3 True
我希望Column C
顯示以下內容:
Column A Column B Column C
1 True True
1 False True
1 False True
2 False False
2 False False
3 False True
3 True True
換句話說,對於Column A
中的每個唯一值,並且如果Column B
中的任何相應值是True
,我希望Column C
中的所有值到 state True
。
在對各種公式進行了多次不同嘗試之后,我想我可能會發現與以下公式接近的東西,但它對每個單元格都返回True
。 我不確定我錯過了什么。
=+IF(AND(UNIQUE($A$1:$A$7)),COUNTIF($B$1:$B$7,"TRUE")>0,1)
我的數據沒有任何缺失值。
我已經在這個網站上搜索了我正在嘗試的內容,但上面的公式是我能找到的最接近的公式。 這個線程很接近,但不是我想要的。
我知道我可以使用以下公式手動執行此操作,但是Column A
中有超過 21K 的唯一值,如果不需要,我不想手動執行此操作。
=+COUNTIF($B$1:$B$3,"TRUE")>0
如果這在 Python 中更容易執行,那么該代碼將很有幫助。 我是 Python 的新手,對 Excel 更熟悉,但了解 Python 可能更容易、更快捷。
這就是我在 pandas 中處理這個問題的方式。
print(df)
#note i've added in a non duplicated row for testing.
Column_A Column_B
0 1 True
1 1 False
2 1 False
3 2 False
4 2 False
5 3 False
6 3 True
7 4 True
首先,我將編寫兩個 boolean 表達式,第一個 - 查看是否有任何值重復,第二個查看 Column_B 是否包含任何 True 值。 如果兩者都等於 True 我想將 A 列中的所有 ID 傳遞到列表中。
vals = df.loc[df.duplicated(subset=["Column_A"], keep=False)
& df["Column_B"].eq(True),
"Column_A"].tolist()
print(vals)
[1, 3]
現在我們知道了值是什么,我們可以編寫一個簡單的 boolean 賦值。
df['Column_C'] = df['Column_A'].isin(vals)
print(df)
Column_A Column_B Column_C
0 1 True True
1 1 False True
2 1 False True
3 2 False False
4 2 False False
5 3 False True
6 3 True True
7 4 True False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.