![](/img/trans.png)
[英]How to delete row in pandas dataframe based on condition if string is found in cell value of type list?
[英]How to append value to list in single cell in Pandas dataframe based on condition
我想根据条件将 append 的值添加到我的 dataframe 中的列表中。
样本df:
姓名 | 列表 |
---|---|
彼得 | [一,公元前] |
乔治 | [d, ef] |
如果名称是 George,我想将值 [g, h] 添加到列表列。
所需的 output:
姓名 | 列表 |
---|---|
彼得 | [一,公元前] |
乔治 | [d, ef, g, h] |
有什么建议么?
使用 cutom lambda function 通过掩码将值添加到列表中:
L = ['g','h']
m = df['Name'].eq('George')
df['List'] = df['List'].mask(m, df['List'].apply(lambda x: x + L))
print (df)
Name List
0 Peter [a, b, c]
1 George [d, e, f, g, h]
或者:
df.loc[m, 'List'] = df.loc[m, 'List'].apply(lambda x: x + L)
或者:
df['List'] = np.where(m, df['List'].apply(lambda x: x + L), df['List'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.