Python pandas:将选定列保持为DataFrame而不是Series

75 python pandas

从pandas DataFrame(例如df.iloc[:, 0],df['A']df.A等)中选择单个列时,生成的向量会自动转换为Series而不是单列DataFrame.但是,我正在编写一些将DataFrame作为输入参数的函数.因此,我更喜欢处理单列DataFrame而不是Series,以便函数可以假定df.columns可以访问.现在我必须通过使用类似的东西显式地将Series转换为DataFrame pd.DataFrame(df.iloc[:, 0]).这似乎不是最干净的方法.是否有更优雅的方式直接从DataFrame索引,以便结果是单列DataFrame而不是Series?

And*_*den 88

正如@Jeff提到的,有几种方法可以做到这一点,但我建议使用loc/iloc更明确(如果你尝试一些不明确的事情,请尽早提出错误):

In [10]: df = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 'B'])

In [11]: df
Out[11]:
   A  B
0  1  2
1  3  4

In [12]: df[['A']]

In [13]: df[[0]]

In [14]: df.loc[:, ['A']]

In [15]: df.iloc[:, [0]]

Out[12-15]:  # they all return the same thing:
   A
0  1
1  3
Run Code Online (Sandbox Code Playgroud)

后两个选项消除了整数列名称的歧义(正是为什么创建了loc/iloc).例如:

In [16]: df = pd.DataFrame([[1, 2], [3, 4]], columns=['A', 0])

In [17]: df
Out[17]:
   A  0
0  1  2
1  3  4

In [18]: df[[0]]  # ambiguous
Out[18]:
   A
0  1
1  3
Run Code Online (Sandbox Code Playgroud)

  • @sparc_spread http://pandas.pydata.org/pandas-docs/stable/indexing.html#basics"您可以将列表列表传递给[],以按顺序选择列." 我不确定这是否有名字! (3认同)
  • 很抱歉打扰你,但这只是一个非常快速的问题.我看到额外的`[]`如何使结果成为`DataFrame`而不是`Series`,但是在pandas docs中讨论了这种索引语法?我只是试图获得这种索引技术的"官方"名称,以便我真正理解它.谢谢! (2认同)

Sum*_*rus 6

正如Andy Hayden 所建议的那样,使用 .iloc/.loc 索引出(单列)数据帧是一种可行的方法;还有一点需要注意的是如何表达索引位置。使用列出的索引标签/位置,同时指定要索引为 Dataframe 的参数值;不这样做将返回一个“pandas.core.series.Series”

输入:

    A_1 = train_data.loc[:,'Fraudster']
    print('A_1 is of type', type(A_1))
    A_2 = train_data.loc[:, ['Fraudster']]
    print('A_2 is of type', type(A_2))
    A_3 = train_data.iloc[:,12]
    print('A_3 is of type', type(A_3))
    A_4 = train_data.iloc[:,[12]]
    print('A_4 is of type', type(A_4))
Run Code Online (Sandbox Code Playgroud)

输出:

    A_1 is of type <class 'pandas.core.series.Series'>
    A_2 is of type <class 'pandas.core.frame.DataFrame'>
    A_3 is of type <class 'pandas.core.series.Series'>
    A_4 is of type <class 'pandas.core.frame.DataFrame'>
Run Code Online (Sandbox Code Playgroud)


Nul*_*ue_ 6

已经提到了这三种方法:

pd.DataFrame(df.loc[:, 'A'])  # Approach of the original post
df.loc[:,[['A']]              # Approach 2 (note: use iloc for positional indexing)
df[['A']]                     # Approach 3
Run Code Online (Sandbox Code Playgroud)

pd.Series.to_frame() 是另一种方法。

因为它是一种方法,所以可以用在上面第二种和第三种方法不适用的情况下。特别是,当将某种方法应用于数据框中的列并且您希望将输出转换为数据框而不是系列时,它非常有用。例如,在 Jupyter Notebook 中,系列不会有漂亮的输出,但数据框会有。

# Basic use case: 
df['A'].to_frame()

# Use case 2 (this will give you pretty output in a Jupyter Notebook): 
df['A'].describe().to_frame()

# Use case 3: 
df['A'].str.strip().to_frame()

# Use case 4: 
def some_function(num): 
    ...

df['A'].apply(some_function).to_frame()
Run Code Online (Sandbox Code Playgroud)