我想从Pandas DataFrame中获得列标题的列表。DataFrame将来自用户输入,所以我不知道有多少列或它们将被称为什么。

例如,如果我有一个这样的数据帧:

>>> my_dataframe
    y  gdp  cap
0   1    2    5
1   2    3    9
2   8    7    2
3   3    4    7
4   6    7    7
5   4    8    3
6   8    2    8
7   9    9   10
8   6    6    4
9  10   10    7

我会得到一个这样的列表:

>>> header_list
['y', 'gdp', 'cap']

当前回答

我做了一些快速测试,也许不出意外,使用datafframe .columns.values.tolist()的内置版本是最快的:

In [1]: %timeit [column for column in df]
1000 loops, best of 3: 81.6 µs per loop

In [2]: %timeit df.columns.values.tolist()
10000 loops, best of 3: 16.1 µs per loop

In [3]: %timeit list(df)
10000 loops, best of 3: 44.9 µs per loop

In [4]: % timeit list(df.columns.values)
10000 loops, best of 3: 38.4 µs per loop

(尽管如此,我仍然非常喜欢这个列表(数据框架),所以感谢EdChum!)

其他回答

扩展可迭代解包(Python 3.5+): [*df]和Friends

Python 3.5引入了解包泛化(PEP 448)。因此,下面的操作都是可能的。

df = pd.DataFrame('x', columns=['A', 'B', 'C'], index=range(5))
df

   A  B  C
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

如果你想要一个列表....

[*df]
# ['A', 'B', 'C']

或者,如果你想要一组,

{*df}
# {'A', 'B', 'C'}

如果你想要一个元组,

*df,  # Please note the trailing comma
# ('A', 'B', 'C')

或者,如果你想把结果存储在某个地方,

*cols, = df  # A wild comma appears, again
cols
# ['A', 'B', 'C']

... 如果你是那种把咖啡转换成打字声音的人,好吧,这将更有效地消耗你的咖啡;)

附注:如果性能很重要,你会想要抛弃 上述解决方案有利于 .tolist df.columns.to_numpy () () # [' a ', ' b ', ' c '] 这与Ed Chum的答案相似,但更新了 V0.24,其中.to_numpy()优先于.values的使用。看到 这个答案(由我)为更多的信息。

目视检查

因为我在其他回答中已经看到过这个问题,所以可以使用可迭代解包(不需要显式循环)。

print(*df)
A B C

print(*df, sep='\n')
A
B
C

其他方法的批判

对于可以在单行中完成的操作,不要使用显式for循环(列表推导式是可以的)。

接下来,使用sorted(df)不会保留列的原始顺序。为此,应该使用list(df)。

其次,list(df.columns)和list(df.columns.values)是不好的建议(就当前版本v0.24而言)。Index(从df.columns返回)和NumPy数组(从df.columns.values返回)都定义了.tolist()方法,该方法更快,更习惯。

最后,对于Python 3.4或更早版本,在扩展解包不可用的情况下,应该只使用列表(list(df))作为上述方法的简洁替代。

%%timeit
final_df.columns.values.tolist()
948 ns ± 19.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%%timeit
list(final_df.columns)
14.2 µs ± 79.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%%timeit
list(final_df.columns.values)
1.88 µs ± 11.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%%timeit
final_df.columns.tolist()
12.3 µs ± 27.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%%timeit
list(final_df.head(1).columns)
163 µs ± 20.6 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

最简单的选择是: List (my_datafframe .columns)或my_datafframe .columns.tolist()

不需要上面复杂的东西:)

>>> list(my_dataframe)
['y', 'gdp', 'cap']

要在调试器模式下列出数据帧的列,使用列表理解式:

>>> [c for c in my_dataframe]
['y', 'gdp', 'cap']

顺便说一下,你可以简单地使用sorted:

>>> sorted(my_dataframe)
['cap', 'gdp', 'y']

它变得更简单(由Pandas 0.16.0):

df.columns.tolist()

会给你一个很好的列表中的列名。