gpt4 book ai didi

python-2.7 - KeyError : in pandas when trying to change boolean column values into string while using . loc方法

转载 作者:行者123 更新时间:2023-12-03 16:26:59 25 4
gpt4 key购买 nike

我正在运行一个条件循环,根据“单独”列的值在我的 DataFrame (TDF) 中创建一个新列。如果值为 0,则添加字符串“alone”,否则在“alone”列中添加“with family”。我正在使用代码:我收到错误:

tdf['alone'].loc[['alone'] >0]= 'with family'
tdf['alone'].loc[['alone'] ==0] = 'alone'

运行上述行后,我收到以下错误:

KeyError: 'cannot use a single bool to index into setitem'

我提到了这个same question ,我收集到的是我需要 row_indexertdf['alone'].loc[[row_indexer,['alone']] = 'alone'但我不知道如何获取 row_indexer 中的值

最佳答案

pandas.Series.clip

将值剪辑为仅 01 并用它来切片数组

tdf.assign(alone=np.array(['alone', 'with family'])[tdf.alone.clip(0, 1)])

alone col
0 with family 1
1 with family 1
2 with family 9
3 alone 4
4 with family 2
5 alone 3

pandas.Series.map

tdf.assign(alone=tdf.alone.map(lambda x: 'with family' if x else 'alone'))

alone col
0 with family 1
1 with family 1
2 with family 9
3 alone 4
4 with family 2
5 alone 3

map

版本 2

tdf.assign(alone=tdf.alone.map(lambda x: {0: 'alone'}.get(x, 'with family')))

alone col
0 with family 1
1 with family 1
2 with family 9
3 alone 4
4 with family 2
5 alone 3

设置

借自@jezrael

tdf = pd.DataFrame({'alone':[4,4,5,0,5,0],
'col':[1,1,9,4,2,3]})

关于python-2.7 - KeyError : in pandas when trying to change boolean column values into string while using . loc方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52196751/

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