Python 在数据帧中插入序列

Python 在数据帧中插入序列,python,pandas,dataframe,Python,Pandas,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 # indexes become columns. series name beco

当我尝试使用一个系列构造数据帧时,这个系列将成为数据帧中的列

#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
# 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
但当提供序列列表时,所有序列都成为数据帧中的行

#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
# 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
为什么在处理上会有这种差异?为什么一个系列不能始终成为数据帧中的行,而不管是提供列表还是单个系列。我相信熊猫开发者不是一时兴起才这么做的

在创建数据帧之后,如果我尝试附加一个 序列,然后将其追加为行

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

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

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

在我看来,一个
Series
s被解析为column,因为在
DataFrame
中,每一列都是
Series
,带有一些
dtype

:

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


请不要发布文本的图像。作为文本发布。删除图像。我的问题基本上是,为什么熊猫开发者会让这种行为有所不同?为什么一个系列不能始终成为数据帧中的行,而不管是提供列表还是单个系列。@victini-Hmmm,我不明白为什么您认为不同的结构必须返回相同的输出?因为若使用系列列表,它的工作方式是相同的,就像我的答案一样,但若使用不同的列表,则预期会有不同的输出。但我不是熊猫开发人员,所以只添加了我的想法。当我们尝试使用append函数将单个系列插入到数据帧中时,它也会被追加为行。那么为什么只在一种情况下,它会变成列?编辑了帖子。@victini-它应该与函数一起添加新行-文档说
将其他行附加到此帧的末尾,返回一个新对象。