Python pandas -> select 按列名称中的条件
Python pandas -> select by condition in columns name
我的 df 包含列名:'a'、'b'、'c' ... 'z'.
print(my_df.columns)
Index(['a', 'b', 'c', ... 'y', 'z'],
dtype='object', name=0)
我有确定应该显示哪些列的功能。例如:
start = con_start()
stop = con_stop()
print(my_df.columns >= start) & (my_df <= stop)
我的结果是:
[False False ... False False False False True True
True True False False]
我的目标是只显示满足我条件的列的数据框。
如果开始 = 'a' 和停止 = 'b',我想要:
0 a b
index1 index2
New York New York 0.000000 0.000000
California Los Angeles 207066.666667 214466.666667
Illinois Chicago 138400.000000 143633.333333
Pennsylvania Philadelphia 53000.000000 53633.333333
Arizona Phoenix 111833.333333 114366.666667
您可以使用切片通过 .loc 实现此目的:
df.loc[:,'a':'b']
生成要显示的列列表:
cols = [x for x in my_df.columns if start <= x <= stop]
在您的 DataFrame 中仅使用这些列:
my_df[cols]
假设 result
是您的 [true/false]
数组并且 letters
是 [a...z]
:
res=[letters[i] for i,r in enumerate(result) if r]
new_df=df[res]
我想让它变得健壮,并尽可能少地使用假设。
选项 1
使用 iloc
和数组切片
假设:
my_df.columns.is_unique
计算结果为 True
- 列已经有序
start = df.columns.get_loc(con_start())
stop = df.columns.get_loc(con_stop())
df.iloc[:, start:stop + 1]
选项 2
使用 loc
和布尔切片
假设:
- 列值具有可比性
start = con_start()
stop = con_stop()
c = df.columns.values
m = (start <= c) & (stop >= c)
df.loc[:, m]
如果您的条件与示例中所示的复杂程度相似,则无需使用任何其他功能,只需进行过滤即可,例如
sweet_and_red_fruit = fruit[(fruit[sweet == 1) & (fruit["colour"] == "red")]
print(sweet_and_red_fruit)
或者如果你只想打印
print(fruit[(fruit[sweet == 1) & (fruit["colour"] == "red")])
我的 df 包含列名:'a'、'b'、'c' ... 'z'.
print(my_df.columns)
Index(['a', 'b', 'c', ... 'y', 'z'],
dtype='object', name=0)
我有确定应该显示哪些列的功能。例如:
start = con_start()
stop = con_stop()
print(my_df.columns >= start) & (my_df <= stop)
我的结果是:
[False False ... False False False False True True
True True False False]
我的目标是只显示满足我条件的列的数据框。 如果开始 = 'a' 和停止 = 'b',我想要:
0 a b
index1 index2
New York New York 0.000000 0.000000
California Los Angeles 207066.666667 214466.666667
Illinois Chicago 138400.000000 143633.333333
Pennsylvania Philadelphia 53000.000000 53633.333333
Arizona Phoenix 111833.333333 114366.666667
您可以使用切片通过 .loc 实现此目的:
df.loc[:,'a':'b']
生成要显示的列列表:
cols = [x for x in my_df.columns if start <= x <= stop]
在您的 DataFrame 中仅使用这些列:
my_df[cols]
假设 result
是您的 [true/false]
数组并且 letters
是 [a...z]
:
res=[letters[i] for i,r in enumerate(result) if r]
new_df=df[res]
我想让它变得健壮,并尽可能少地使用假设。
选项 1
使用 iloc
和数组切片
假设:
my_df.columns.is_unique
计算结果为True
- 列已经有序
start = df.columns.get_loc(con_start())
stop = df.columns.get_loc(con_stop())
df.iloc[:, start:stop + 1]
选项 2
使用 loc
和布尔切片
假设:
- 列值具有可比性
start = con_start()
stop = con_stop()
c = df.columns.values
m = (start <= c) & (stop >= c)
df.loc[:, m]
如果您的条件与示例中所示的复杂程度相似,则无需使用任何其他功能,只需进行过滤即可,例如
sweet_and_red_fruit = fruit[(fruit[sweet == 1) & (fruit["colour"] == "red")]
print(sweet_and_red_fruit)
或者如果你只想打印
print(fruit[(fruit[sweet == 1) & (fruit["colour"] == "red")])