gpt4 book ai didi

python - Pandas 中列名的排序

转载 作者:行者123 更新时间:2023-11-30 22:13:56 25 4
gpt4 key购买 nike

我对 DataFrame 的行为有点困惑

例如:

df = pd.DataFrame(data=np.random.random(size=(5,3)), 
columns={'a', 'b', 'c'})

为什么默认输出是:

df =      c         a         b
0 0.325172 0.831253 0.151912
1 0.558476 0.177249 0.906136
2 0.516089 0.069013 0.370251
3 0.440246 0.154116 0.494690
4 0.793981 0.409526 0.885879

而不是列的有序列表('a'、'b'、'c')

(Python 3.6,Pandas 0.23)

最佳答案

您传递了一组列名称,这些名称不一定保留顺序,如果您传递了一个列表,那么它将执行您想要的操作:

In[32]:
df = pd.DataFrame(data=np.random.random(size=(5,3)),
columns=['a', 'b', 'c'])
df

Out[32]:
a b c
0 0.227711 0.410568 0.795012
1 0.624751 0.708471 0.152641
2 0.901483 0.967297 0.884749
3 0.353622 0.220706 0.031015
4 0.628634 0.128421 0.679261

关于python - Pandas 中列名的排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50642290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com