![](/img/trans.png)
[英]Keep certain columns in a pandas DataFrame, deleting everything else that fall within the column name
[英]Keep certain columns in a pandas DataFrame, deleting everything else
假設我有一個數據表
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 列刪除所有其他內容並保持結構。 我怎么能用熊貓做到這一點? 我想我了解如何刪除單個列,但我不知道如何保存一些選擇並刪除所有其他列。
如果你有一個列列表,你可以選擇那些:
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
如何將某些列保留在 pandas DataFrame 中,刪除其他所有內容?
這個問題的答案與“如何刪除 pandas DataFrame 中的某些列?”的答案相同。 以下是到目前為止提到的一些附加選項,以及時間安排。
DataFrame.loc
如其他答案所述,一個簡單的選擇是選擇,
# Setup.
df
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
cols_to_keep = [3,5]
df[cols_to_keep]
3 5
A x x
B x x
C x x
或者,
df.loc[:, cols_to_keep]
3 5
A x x
B x x
C x x
axis=1
或'columns'
( DataFrame.reindex
)的 DataFrame.reindex 但是,我們也有reindex
,在最近的版本中,您指定axis=1
刪除:
df.reindex(cols_to_keep, axis=1)
# df.reindex(cols_to_keep, axis='columns')
# for versions < 0.21, use
# df.reindex(columns=cols_to_keep)
3 5
A x x
B x x
C x x
在舊版本上,您還可以使用reindex_axis
: df.reindex_axis(cols_to_keep, axis=1)
。
DataFrame.drop
另一種選擇是使用drop
通過pd.Index.difference
選擇列:
# df.drop(cols_to_drop, axis=1)
df.drop(df.columns.difference(cols_to_keep), axis=1)
3 5
A x x
B x x
C x x
這些方法在性能方面大致相同; 對於較小的 N, reindex
更快,而對於較大的 N, drop
更快。性能是相對的,因為 Y 軸是對數的。
設置和代碼
import pandas as pd
import perfplot
def make_sample(n):
np.random.seed(0)
df = pd.DataFrame(np.full((n, n), 'x'))
cols_to_keep = np.random.choice(df.columns, max(2, n // 4), replace=False)
return df, cols_to_keep
perfplot.show(
setup=lambda n: make_sample(n),
kernels=[
lambda inp: inp[0][inp[1]],
lambda inp: inp[0].loc[:, inp[1]],
lambda inp: inp[0].reindex(inp[1], axis=1),
lambda inp: inp[0].drop(inp[0].columns.difference(inp[1]), axis=1)
],
labels=['__getitem__', 'loc', 'reindex', 'drop'],
n_range=[2**k for k in range(2, 13)],
xlabel='N',
logy=True,
equality_check=lambda x, y: (x.reindex_like(y) == y).values.all()
)
您可以為DataFrame
重新分配一個新值df
:
df = df.loc[:,[3, 5]]
只要沒有其他對原始DataFrame
的引用,舊的DataFrame
就會被垃圾收集。
請注意,使用df.loc
時,索引由標簽指定。 因此上面的3
和5
不是序數,它們代表列的標簽名稱。 如果您希望按序號索引指定列,請使用df.iloc
。
對於那些正在尋找就地執行此操作的方法的人:
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
另一種方法是使用filter
:
In [5]: df.filter([3, 5])
Out[5]:
3 5
A x x
B x x
C x x
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.