short['SOURCE'] = None
for x in range(len(short)):
if (short['AMOUNT'].iloc[x] > 0) & (len(short['ACCOUNT'].iloc[x]) >1):
short['SOURCE'].iloc[x] = short['ACCOUNT'].iloc[x][1]
elif short['AMOUNT'].iloc[x] > 0:
short['SOURCE'].iloc[x] = "Guy"
else:
short['SOURCE'].iloc[x] = short['MERCHANT'].iloc[x]
目标:
查看 ACCOUNT 和 SOURCE 列。
如果 ACCOUNT 有 2 个字符串且 source 为正,则将 SOURCE 设置为第二个字符串
如果 ACCOUNT 有 1 个字符串,则将 SOURCE 设置为该字符串
如果 AMOUNT 为负数,请将 SOURCE 设置为 MERCHANT 列。
这是一个 super 丑陋、 super 黑客、 super 慢的解决方案。还有更好的吗?
最佳答案
我相信你需要numpy.select
,字符串长度 str.len
:
short = pd.DataFrame({'AMOUNT':[0,0,5,8],
'ACCOUNT':['a','a s','d f','f'],
'MERCHANT':list('abcd')})
m1 = short['AMOUNT'] > 0
m2 = m1 & (short['ACCOUNT'].str.len() > 1)
short['SOURCE'] = np.select([m2, m1], [short['ACCOUNT'], 'Guy'], default = short['MERCHANT'])
print (short)
ACCOUNT AMOUNT MERCHANT SOURCE
0 a 0 a a
1 a s 0 b b
2 d f 5 c d f
3 f 8 d Guy
关于python - 使用 pandas 行的内容创建另一个 pandas 行(帮助我优化这个非常丑陋的函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47151194/