gpt4 book ai didi

python - 如何将一列数据框或单行数据框作为数据框或系列返回?

转载 作者:行者123 更新时间:2023-12-02 18:31:56 24 4
gpt4 key购买 nike

给df,

df = pd.DataFrame({'col1':np.arange(6), 'col2':[*'abcdef']})

col1 col2
0 0 a
1 1 b
2 2 c
3 3 d
4 4 e
5 5 f

然后在选择单个列时,使用:

df['col1']
# returns a pd.Series

0 0
1 1
2 2
3 3
4 4
5 5
Name: col1, dtype: int32

同样选择单行时,

df.loc[0]
# returns a pd.Series

col1 0
col2 a
Name: 0, dtype: object

我们如何强制单列或单行选择返回 pd.DataFrame?

最佳答案

你也可以使用to_frame:

# One column
>>> df['col1'].to_frame()
col1
0 0
1 1
2 2
3 3
4 4
5 5

# One row
>>> df.loc[0].to_frame().T
col1 col2
0 0 a

关于python - 如何将一列数据框或单行数据框作为数据框或系列返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69305736/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com