我有以下代码
import pandas as pd
d = [{'points': 50, 'time': '5:00', 'year': 2010},
{'points': 25, 'time': '6:00', 'month': "february"},
{'points': 90, 'time': '9:00', 'month': 'january'},
{'points_h1': 20, 'month': 'june'}]
df = pd.DataFrame(d)
df['auditor'] = None
df.loc[df['points'] == 50, 'auditor'] = (1, 2)
print(df)
print(df.loc[df['points'] == 50, 'auditor'])
我想用None
启动一个新列并有条件地用tuple
更新其值,但出现以下错误
ValueError: cannot set using a multi-index selection indexer with a different length than the value
我渴望的结果是
month points points_h1 time year auditor
0 NaN 50 NaN 5:00 2010 (1,2)
1 february 25 NaN 6:00 NaN None
2 january 90 NaN 9:00 NaN None
3 june NaN 20 NaN NaN None
我可以怎样做
由于您无法确定条件只返回一行或多行,因此最好创建一系列元组,并根据条件返回的行数重复该元组:
为了了解我的意思,让我们考虑第二行也有{{CD1>}为50:
您还可以使用
np.where()
,这是一个很好的条件函数:或者在使用
.assign()
创建数据帧时,在一行中:根据您的评论,如果您想手动创建条件和结果,然后通过
np.where()
循环,那么您可以这样做:见Anky的评论。而不是:
您可以使用
np.select
来避免循环。这是一个更像Python的游戏。做到这一点的有效方法:相关问题 更多 >
编程相关推荐