<p>您可以将单行数据帧(仍会产生数据帧)转置,然后将结果<a href="http://pandas.pydata.org/pandas-docs/stable/dsintro.html?highlight=squeeze#squeezing" rel="noreferrer">squeeze</a>成一个序列(与<code>to_frame</code>相反)。</p>
<pre><code>df = pd.DataFrame([list(range(5))], columns=["a{}".format(i) for i in range(5)])
>>> df.T.squeeze() # Or more simply, df.squeeze() for a single row dataframe.
a0 0
a1 1
a2 2
a3 3
a4 4
Name: 0, dtype: int64
</code></pre>
<p><strong>注意:</strong>要容纳@ian提出的点(即使不在操作问题中),请测试数据帧的大小。我假设<code>df</code>是一个数据帧,但是边的大小写是一个空数据帧、一个形状(1,1)的数据帧和一个具有多行的数据帧,在这种情况下,用户应该实现其所需的功能。</p>
<pre><code>if df.empty:
# Empty dataframe, so convert to empty Series.
result = pd.Series()
elif df.shape == (1, 1)
# DataFrame with one value, so convert to series with appropriate index.
result = pd.Series(df.iat[0, 0], index=df.columns)
elif len(df) == 1:
# Convert to series per OP's question.
result = df.T.squeeze()
else:
# Dataframe with multiple rows. Implement desired behavior.
pass
</code></pre>
<p>这也可以按照@themachinist提供的答案来简化。</p>
<pre><code>if len(df) > 1:
# Dataframe with multiple rows. Implement desired behavior.
pass
else:
result = pd.Series() if df.empty else df.iloc[0, :]
</code></pre>