簡體   English   中英

如何將單列 Pandas DataFrame 轉換為 Series

[英]How to convert a single column Pandas DataFrame into Series

我有以下數據框:

import pandas as pd
d = {'gene' : ['foo','bar'],'score' : [4., 3.,]}
df = pd.DataFrame(d)
df.set_index('gene',inplace=True)

這使得:

In [56]: df
Out[56]:
      score
gene
foo       4
bar       3
In [58]: type(df)
Out[58]: pandas.core.frame.DataFrame

我想做的是把它變成一個系列。 我希望它返回:

gene
foo       4
bar       3
#pandas.core.series.Series

我試過這個,但它不起作用:

In [64]: type(df.iloc[0:,])
Out[64]: pandas.core.frame.DataFrame

In [65]: df.iloc[0:,]
Out[65]:
      score
gene
foo       4
bar       3

正確的做法是什么?

s = df.squeeze()
>>> s
gene
foo    4
bar    3
Name: score, dtype: float64

要將其恢復為數據幀:

>>> s.to_frame()
      score
gene       
foo       4
bar       3

嘗試交換括號中的索引:

df.iloc[:,0]

這應該有效。

交換索引可以輕松解決問題:

In [64]: type(df.iloc[0:,])
Out[64]: pandas.core.frame.DataFrame

In [65]: df.iloc[[:,0] // Swaped the indices
Out[65]:
        score
gene
foo       4
bar       3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM