【问题标题】:Insertion of Series in a DataFrame在 DataFrame 中插入系列
【发布时间】:2018-07-30 12:43:21
【问题描述】:

当我尝试使用一个系列构建 DataFrame 时,该系列将成为 DataFrame 中的列。

#name of series become column. All indexes of series become indexes
s= pd.Series({'a':1,'b':2,'c':3}, name='joe')
df=pd.DataFrame(s)
print(df)
     joe
a     1
b     2
c     3

但是当提供一个系列列表时,所有系列都成为 DataFrame 中的行。

# indexes become columns. series name become row name
s1= pd.Series({'a':1,'b':2,'c':3}, name='joe')
s2=pd.Series({'a':4,'b':5,'c':6}, name='john')
slist=[s1,s2]
df=pd.DataFrame(slist)
print(df)
     a    b   c
joe  1    2   3
john 4    5   6

为什么在处理上有这种差异?为什么一个系列不能总是成为 DataFrame 中的行,无论是提供列表还是单个系列。我相信 Pandas 的开发者并不是一时兴起。

创建 DataFrame 后,如果我尝试附加一个 系列,然后它被附加为行。

import pandas as pd
s1= pd.Series({'a':1,'b':2,'c':3}, name='s1')
s2=pd.Series({'a':4,'b':5,'c':6}, name='s2')
slist=[s1,s2]
df=pd.DataFrame(slist)
s=pd.Series({'b':1}, name='s3')
df=df.append(s)
print(df)

     a    b    c
s1  1.0  2.0  3.0
s2  4.0  5.0  6.0
s3  NaN  1.0  NaN

【问题讨论】:

  • 请不要张贴文字图片。作为文本本身发布。
  • 删除的图片。

标签: python pandas dataframe


【解决方案1】:

有区别,因为在第二个示例中使用Series的列表,所以如果需要在第一个行中需要一个元素列表[s]

s = pd.Series({'a':1,'b':2}, name='joe')
#list of Series
df = pd.DataFrame([s])
print (df)
     a  b
joe  1  2

s1 = pd.Series({'a':1,'b':2}, name='joe')
s2 = pd.Series({'a':4,'b':5}, name='john')
#list of Series
df = pd.DataFrame([s1,s2])
print (df)
      a  b
joe   1  2
john  4  5

在我看来,一个Seriess 被解析为列,因为在DataFrame 中,每一列都是Series 和一些dtype

DataFrame:

DataFrame 是一种二维标记数据结构,具有可能不同类型的列。您可以将其视为电子表格或 SQL 表,或 Series 对象的字典。

【讨论】:

  • 我的问题基本上是,为什么 Pandas 开发人员使这种行为有所不同?为什么一个系列不能总是成为 DataFrame 中的行,无论是提供列表还是单个系列。
  • @victini - 嗯,我不明白你为什么认为不同的结构必须返回相同的输出?因为如果使用系列列表,它的工作方式相同,就像我的回答一样,但如果使用不同,则预期会有不同的输出。但我不是 pandas 开发者,所以只添加了我的想法。
  • 当我们尝试使用 append 函数将单个系列插入 DataFrame 时,它​​也会被追加为行。那为什么只是在一种情况下,它变成了列?
  • 编辑了帖子。
  • @victini - 预计功能 append 添加新行 - 文档说 Append rows of other to the end of this frame, returning a new object.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多