我有下面的dataframe,其中前三列具有不应更改的特定名称(“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'})
我想选择所有编号的列(列索引3-7),这些列包含第一行中的值1。
df2 = df.loc[0, df.iloc[0, 3:] == 1]
这会引发以下错误:AssertionError
之后,我想使用来自df2的索引,这些索引表示符合第1行(例如第3和第5列)值1标准的列,用于从第二行中选择这些列,并检查这些列是否也具有值1。
df3 = df.loc[1, df.iloc[1, df2.index] == 1]
这会引发以下错误:IndexError:.iloc需要数字索引器,got 3 5
最后的预期输出应该是只有来自第2行的列索引3满足值1的标准,这是基于以下事实:从第1行,只有列索引3和5的值为1。
我该怎么做?
发布于 2022-02-18 09:24:48
使用:
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')
发布于 2022-02-18 09:30:51
一种选择:
# 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://stackoverflow.com/questions/71171055
复制相似问题