【问题标题】:Selecting a dataframe column without dropping the label选择数据框列而不删除标签
【发布时间】:2014-05-26 12:13:01
【问题描述】:

如何在不删除列名的情况下选择数据框列 df['col']?

df
index colname col1 col2 col3
  1             0    1    2
  2             3    4    5
  3             6    7    8
  4             9   10   11

期望的输出:

df['col1']
index colname col1 
  1             0   
  2             3    
  3             6    
  4             9

编辑: 如正确回答, df[['col1']] 完成了这项工作......现在有点棘手。如果列是多索引的怎么办?

df    grpname A            B            ...  Z
index colname cA1 ... cAN  cB1 ... cBN  ...  cZ1 ... cZN
  1           a11 ... a1N  b11 ... b1N  ...  z11 ... z1N
  2           a21 ... a2N  b21 ... b2N  ...  z21 ... z2N
  3           a31 ... a3N  b31 ... b3N  ...  z31 ... z3N
  4           a41 ... a4N  b41 ... b4N  ...  z41 ... z4N

我想得到

df    grpname A            
index colname cA1 cA2  
  1           a11 a12 
  2           a21 a22 
  3           a31 a32  
  4           a41 a42

看起来 .xs() 只允许我检索某个列,即 df.xs( ('A', 'cAi'), level=('grpname','colname'), axis=1, drop_level =False) ),而 df[['A']]['cA1':'cAi'] 也不起作用?

【问题讨论】:

  • df[['col']] 没有做你想做的事吗?
  • df[['col']] 应该仍然可以工作我不明白你到底想要什么,你能发布复制数据和输出的代码
  • 现在可能更清楚了。我想在不删除标签的情况下获得只有两个“cols”的“A”组。
  • 请发布重现数据和组的代码

标签: python pandas


【解决方案1】:

对于单列选择,df['col'] 将返回一个系列,如果您想保留列名,则需要双下标,这将返回一个数据框:

In [2]:

import pandas as pd
pd.set_option('display.notebook_repr_html', False)
import io
temp = """index col1 col2 col3
  1             0    1    2
  2             3    4    5
  3             6    7    8
  4             9   10   11"""
df = pd.read_csv(io.StringIO(temp), sep='\s+',index_col=[0])
df
Out[2]:
       col1  col2  col3
index                  
1         0     1     2
2         3     4     5
3         6     7     8
4         9    10    11
In [4]:

df[['col1']]
Out[4]:
       col1
index      
1         0
2         3
3         6
4         9

对比:

In [5]:

df['col1']
Out[5]:
index
1        0
2        3
3        6
4        9
Name: col1, dtype: int64

编辑 正如@joris 指出的那样,您可以看到名称显示在输出的底部,名称不会丢失,因为只是不同的输出

【讨论】:

  • 请注意,列名不是“丢失”,不同之处仅在于表示形式。系列仍然有名称,但在表示中,这是在底部。
  • 谢谢,我没想到...你能检查一下编辑,看看你能不能回答这个多索引列吗?
【解决方案2】:

如果您确定每列占用的空间,有一种方法可以做到这一点。 这里是the example ...

np.loadtxt("df.txt",
    dtype={
        'names': ('index', 'colname', 'col1', 'col2', 'col3'),
        'formats': (np.float, np.string, np.float, np.float, np.float)},
        delimiter= ' ', skiprows=1)

【讨论】:

  • 这不是关于读取文件,而是关于索引现有数据帧
猜你喜欢
  • 2016-04-16
  • 2021-06-13
  • 1970-01-01
  • 2020-07-23
  • 2012-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多