【发布时间】: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
【问题讨论】:
-
请不要张贴文字图片。作为文本本身发布。
-
删除的图片。