[英]How to convert pandas Series to DataFrame
我有一個 pandas 系列作為 se:
wind yes
humidity high
weather sunny
temp hot
conclusion bad
Name: 1, dtype: object
我想將其轉換為 dataframe,例如:
| weather| temp | humidity | wind | conclusion
0 | sunny | hot | high | yes | bad
我試過了
pd.DataFrame(se)
但事實證明是別的東西
wind yes
humidity high
weather sunny
temp hot
conclusion bad
使用to_frame
並轉置您的新 dataframe:
df = sr.to_frame(0).T
print(df)
# Output:
wind humidity weather temp conclusion
0 yes high sunny hot bad
設置
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
使用它,它可能會有所幫助:)
se.to_frame()
您很可能使用 .loc[0] 或 .iloc[0] 選擇了原始數據框的一行。 嘗試使用雙括號將 select 單行從 dataframe 用作 dataframe 而不是轉換為系列。
df.iloc[[0]]
或者
df.loc[[0]]
MVCE:
df = pd.DataFrame({'Col1':[*'ABC'],
'Col2':'Alpha Bravo Charlie'.split(' '),
'Col3': [1,2,3]})
df.loc[0]
輸出一個 pd.Series:
Col1 A
Col2 Alpha
Col3 1
Name: 0, dtype: object
現在嘗試雙括號:
df.loc[[0]]
輸出一個單行 pd.Dataframe:
Col1 Col2 Col3
0 A Alpha 1
而且,同樣與.iloc。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.