gpt4 book ai didi

python - 在 Python DataFrame 上应用 lambda

转载 作者:太空宇宙 更新时间:2023-11-04 09:42:34 25 4
gpt4 key购买 nike

我有一个像

这样的 Python Pandas DataFrame
>>> df
classification like
0 flower 1
1 flower 0
2 flower 0
3 adventure 1
4 adventure 1

我想创建一个像这样的输出DataFrame

>>> df
classification like liked
0 flower 1 True
1 flower 0 False
2 flower 0 False
3 adventure 1 True
4 adventure 1 True

我在输入 DataFrame 上“应用”Python lambda 函数,如下所示:

>>> df['like'].apply(lambda x: x == 1)

但是我在“喜欢”栏下得到的都是“假”

>>> df
classification like liked
0 flower 1 False
1 flower 0 False
2 flower 0 False
3 adventure 1 False
4 adventure 1 False

任何快速建议都会有所帮助。

>>> df['like'].astype(int)
0 1
1 0
2 0
3 1
4 1
Name: like, dtype: int32

@杰斯雷尔

>>> df['liked'] = df['like'].astype(bool)
>>> df
classification like liked
0 flower 1 True
1 flower 0 True
2 flower 0 True
3 adventure 1 True
4 adventure 1 True

@jezrael : DTypes

>>> df.dtypes
classification object
like object
liked bool
dtype: object

最佳答案

将整数列转换为 bool 值:

print (type(df.loc[0, 'like']))
<class 'numpy.int64'>

df['liked'] = df['like'].astype(bool)

或分配与 1 的比较:

df['liked'] = df['like'] == 1

如果 1 是字符串,通过字符串 '1' 比较:

print (type(df.loc[0, 'like']))
<class 'str'>

df['liked'] = df['like'] == '1'
print (df)
classification like liked
0 flower 1 True
1 flower 0 False
2 flower 0 False
3 adventure 1 True
4 adventure 1 True

关于python - 在 Python DataFrame 上应用 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51102581/

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