我有以下資料框,其中前三列具有不應更改的特定名稱('col1' - 'col3'),編號的列范圍為 3 - 7。
data = [[0, 0.5, 0.5, 1, 0, 1, 0, 0],
[1, 0.5, 0.5, 1, 1, 0, 1, 1],
[2, 0.5, 0.5, 1, 1, 0, 1, 1]]
df = pd.DataFrame(data)
df = df.rename(columns = {0: 'Col1', 1:'Col2', 2: 'Col3'})
我想選擇第一行中包含值 1 的所有編號列(列索引 3-7) 。
df2 = df.loc[0, df.iloc[0, 3:] == 1]
這引發了以下錯誤:AssertionError
之后我想使用 df2 中的索引來表示滿足第 1 行中值 1 標準的列(例如第 3 列和第 5 列),用于從第二行中選擇這些列并檢查這些列是否也具有值 1或不。
df3 = df.loc[1, df.iloc[1, df2.index] == 1]
這會引發以下錯誤:IndexError: .iloc requires numeric indexers, got [3 5]
最終的預期輸出應該是只有第 2 行中的列索引 3 滿足值 1 的標準,因為第 1 行中只有列索引 3 和 5 具有值 1。
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
采用:
df1 = df.iloc[:, 3:]
fin = df1.columns[(df1.iloc[0] == 1) & (df.iloc[1, 3:] == 1)]
print (fin)
Index([3], dtype='object')
原始解決方案:
out = df.columns[3:][df.iloc[0, 3:] == 1]
s = df.loc[1, out]
fin = s.index[s == 1]
print (fin)
Index([3], dtype='object')
uj5u.com熱心網友回復:
一種選擇:
# first row of columns to test (could be a fixed list)
cols = df.loc[0,3:7]
# if not 1, then drop
df2 = df.drop(cols[cols.ne(1)].index, axis=1)
輸出:
Col1 Col2 Col3 3 5
0 0 0.5 0.5 1 1
1 1 0.5 0.5 1 0
2 2 0.5 0.5 1 0
選擇
只需獲取包含 1 的列的名稱:
cols = df.loc[0,3:7] # first row, columns 3 to 7
# or with iloc
# cols = df.iloc[0,3:]
cols[cols.eq(1)].index
# Index([3, 5], dtype='object')
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/427456.html
標籤:Python python-3.x 熊猫 索引
上一篇:當我使用列印功能時,如何減少我在python中的執行時間?
下一篇:戲說領域驅動設計(五)——子域
