【问题标题】:Pandas DataFrame spliced results become seriesPandas DataFrame 拼接结果变成系列
【发布时间】:2017-12-30 09:38:05
【问题描述】:

我想知道在切片数据后是否有办法保留 pandas 数据帧数据类型。

例如,如果我有一个名为 df 的 pandas DataFrame 具有多列,当我对一列进行切片时,它不再是一个 DataFrame 而是一个系列。有没有办法将其保留为数据框?

我的意思是

type(df)
pandas.core.frame.DataFrame

但是

type(df.iloc[:,0])
pandas.core.series.Series

我想绕过它的唯一方法是将其明确地重新定义为数据框。

pd.DataFrame(df.iloc[:,0])

【问题讨论】:

标签: python python-2.7 pandas dataframe


【解决方案1】:

确实有:

type(df.iloc[:,[0]])

将您的列/列作为列表传递,并返回一个数据框。你可以看到区别:

In [288]: df = pd.DataFrame({0 : [1, 2, 3], 1: [3, 4, 5], 2:[4, 5, 6]}); df
Out[288]: 
   0  1  2
0  1  3  4
1  2  4  5
2  3  5  6

In [289]: df.iloc[:, 0]
Out[289]: 
0    1
1    2
2    3
Name: 0, dtype: int64

In [290]: df.iloc[:, [0]]
Out[290]: 
   0
0  1
1  2
2  3

In [291]: type(df.iloc[:, [0]])
Out[291]: pandas.core.frame.DataFrame

【讨论】:

    【解决方案2】:

    我喜欢 COLDSPEED 的回答,但这是另一种方法

    df.iloc[:, 0].to_frame()
    
       0
    0  1
    1  2
    2  3
    

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 2014-01-21
      • 2013-11-09
      • 1970-01-01
      • 2016-08-20
      • 2021-11-22
      • 2017-09-15
      相关资源
      最近更新 更多