假设我有一个数据表
1 2 3 4 5 6 .. n
A x x x x x x .. x
B x x x x x x .. x
C x x x x x x .. x
我想精简它,这样我就只有3列和5列删除了所有其他的并保持了结构。我怎么才能对熊猫这么做呢?我想我知道如何删除单个列,但我不知道如何保存选定的几列并删除所有其他列。
发布于 2013-05-18 03:24:38
如果您有一个列的列表,您可以只选择这些列:
In [11]: df
Out[11]:
1 2 3 4 5 6
A x x x x x x
B x x x x x x
C x x x x x x
In [12]: col_list = [3, 5]
In [13]: df = df[col_list]
In [14]: df
Out[14]:
3 5
A x x
B x x
C x x
发布于 2018-07-11 20:51:23
对于那些正在搜索一种方法来就地执行此操作的人:
from pandas import DataFrame
from typing import Set, Any
def remove_others(df: DataFrame, columns: Set[Any]):
cols_total: Set[Any] = set(df.columns)
diff: Set[Any] = cols_total - columns
df.drop(diff, axis=1, inplace=True)
这将创建数据帧中所有列和应该删除的列的补充。这些都可以安全地删除。Drop即使在空集上也有效。
>>> df = DataFrame({"a":[1,2,3],"b":[2,3,4],"c":[3,4,5]})
>>> df
a b c
0 1 2 3
1 2 3 4
2 3 4 5
>>> remove_others(df, {"a","b","c"})
>>> df
a b c
0 1 2 3
1 2 3 4
2 3 4 5
>>> remove_others(df, {"a"})
>>> df
a
0 1
1 2
2 3
>>> remove_others(df, {"a","not","existent"})
>>> df
a
0 1
1 2
2 3
https://stackoverflow.com/questions/16616141
复制相似问题