简体   繁体   English

如何将 pandas 系列转换为 DataFrame

[英]How to convert pandas Series to DataFrame

I have a pandas Series as se:我有一个 pandas 系列作为 se:

wind      yes
humidity     high
weather    sunny
temp    hot
conclusion    bad
Name: 1, dtype: object

And I want to convert it into a dataframe like:我想将其转换为 dataframe,例如:

  | weather| temp | humidity | wind | conclusion
0 | sunny | hot  | high | yes | bad

I've tried我试过了

pd.DataFrame(se)

but it turns out to be something else但事实证明是别的东西

wind      yes
humidity     high
weather    sunny
temp    hot
conclusion    bad

Use to_frame and transpose your new dataframe:使用to_frame并转置您的新 dataframe:

df = sr.to_frame(0).T
print(df)

# Output:
  wind humidity weather temp conclusion
0  yes     high   sunny  hot        bad

Setup设置

data = {'wind': 'yes',
        'humidity': 'high',
        'weather': 'sunny',
        'temp': 'hot',
        'conclusion': 'bad'}
sr = pd.Series(data, name=1)
print(sr)

# Output
wind            yes
humidity       high
weather       sunny
temp            hot
conclusion      bad
Name: 1, dtype: object

Use this, it might help:)使用它,它可能会有所帮助:)

   se.to_frame()

More than likely you got this series buy selecting a single row of your originaldataframe using.loc[0] or.iloc[0].您很可能使用 .loc[0] 或 .iloc[0] 选择了原始数据框的一行。 Try using double brackets to select a single row from a dataframe as a dataframe instead of converting to a series.尝试使用双括号将 select 单行从 dataframe 用作 dataframe 而不是转换为系列。

df.iloc[[0]]  

or或者

df.loc[[0]]

MVCE: MVCE:

df = pd.DataFrame({'Col1':[*'ABC'], 
              'Col2':'Alpha Bravo Charlie'.split(' '),
              'Col3': [1,2,3]})

df.loc[0]

Outputs a pd.Series:输出一个 pd.Series:

Col1        A
Col2    Alpha
Col3        1
Name: 0, dtype: object

Now try double brackets:现在尝试双括号:

df.loc[[0]]

Outputs a signle row pd.Dataframe:输出一个单行 pd.Dataframe:

  Col1   Col2  Col3
0    A  Alpha     1

And, likewise with.iloc.而且,同样与.iloc。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM