[英]Generating a new variable based on the values of other variables
我有以下數據集
import pandas as pd
df = pd.DataFrame({"ID": [1,1,1,1,1,2,2,2,2,2],
"TP1": [1,2,3,4,5,9,8,7,6,5],
"TP2": [11,22,32,43,53,94,85,76,66,58],
"TP10": [114,222,324,443,535,94,385,76,266,548],
"count": [1,2,3,4,10,1,2,3,4,10]})
print (df)
我想要一個基於 ID、TP 和計數變量的 df 中的“最終”變量。
最終結果將如下所示。
import pandas as pd
import numpy as np
df = pd.DataFrame({"ID": [1,1,1,1,1,2,2,2,2,2], "TP1": [1,2,3,4,5,9,8,7,6,5],
"TP2": [11,22,32,43,53,94,85,76,66,58], "TP10": [114,222,324,443,535,94,385,76,266,548],
"count": [1,2,3,4,10,1,2,3,4,10],
"final" : [71,1836,np.nan,np.nan,1993,291,1832,np.nan,np.nan,1810]})
print (df)
因此,例如, if 的循環將執行以下操作
然后查看 ID 1 的計數 2,TP2 的值應該出現在“final”變量中,依此類推。
我希望我的問題很清楚。 我正在尋找一個循環,因為原始數據集中有 1000 個 TP 變量。
我試圖制作類似以下的代碼,但它完全是垃圾。
for col in df.columns:
if col.startswith('TP') and count == int(col[2:])
df["Final"] = count
謝謝
如果我的理解是正確的,如果count=1
則選擇TP1
,如果count=2
則選擇TP2
等等。
這可以通過numpy.select()
來完成。 請注意,我if f"TP{x}" in df.columns
因為並非所有列TP1, TP2, TP3, ... TP10
在 dataframe 中都可用。 如果所有這些都在您的實際 dataframe 中可用,則不需要此if
語句。
import numpy as np
conds = [df["count"] == x for x in range(1,11) if f"TP{x}" in df.columns]
output = [df[f"TP{x}"] for x in range(1,11) if f"TP{x}" in df.columns]
df["final"] = np.select(conds, output, np.nan)
print(df)
Output:
ID TP1 TP2 TP10 count final
0 1 1 11 114 1 1.0
1 1 2 22 222 2 22.0
2 1 3 32 324 3 NaN
3 1 4 43 443 4 NaN
4 1 5 53 535 10 535.0
5 2 9 94 94 1 9.0
6 2 8 85 385 2 85.0
7 2 7 76 76 3 NaN
8 2 6 66 266 4 NaN
9 2 5 58 548 10 548.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.