为熊猫单元格设置或增加价值 // 优化



提供了一个字符串,例如XYZ我需要在熊猫单元格中设置一个值或根据单元格是否为空来附加它。 如果单元格为空,则值设置为XYZ如果单元格不为空,则我在它前面添加;,例如结果将是notempty;XYZ

我该怎么做? 假设数据帧:

dff = pd.DataFrame({'D':['a','b','','c'],
'E':['d','','','']})
# I would like to add the string:
mystring='XYZ'
condition = (dff['E'] == 'd')
# checking if he cell where I want to add is empty or not
if dff.loc[condition,['D']]['D'][0] == '':
dff.loc[condition,['D']] = mystring
else: 
# the cell is not empty. Hence I have to add ; and the string
content = dff.loc[condition,['D']]['D'][0]
dff.loc[condition,['D']] = content + ';' + mystring

问题是。 这根本不是pythonic-nice。 有什么建议吗?

注意1:我添加了该条件,因为实际上我有很多条件,我无法使用 pd.at,这可能很诱人

您可以使用np.where

dff = pd.DataFrame({'D':['a','b','','c'],
'E':['d','','','']})
mystring='XYZ'
dff["D"] = np.where(dff["D"]=="",mystring,dff["D"]+";"+mystring)
print (dff)
D  E
0  a;XYZ  d
1  b;XYZ   
2    XYZ   
3  c;XYZ  

最新更新