python - 根据 Pandas 列表列中的条件创建新列

标签 python pandas

我有一个包含列表列的数据框:

col_1            
[A, A, A, B, C]
[D, B, C]
[C]
[A, A, A]
NaN
如果列表以 3* A 开头,我想创建新列返回1,如果不返回0:
col_1              new_col           
[A, A, A, B, C]    1
[D, B, C]          0
[C]                0
[A, A, A]          1
NaN                0
我试过这个但没有用:
df['new_col'] = df.loc[df.col_1[0:3] == [A, A, A]]

最佳答案

因为有一些非列表值可以使用 if-else 0 的 lambda 函数如果没有列出:

print (df['col_1'].map(type))
0     <class 'list'>
1     <class 'list'>
2     <class 'list'>
3     <class 'list'>
4    <class 'float'>
Name: col_1, dtype: object
f = lambda x: int((x[:3]) == ['A','A','A']) if isinstance(x, list) else 0
df['new_col'] = df['col_1'].map(f)
#alternative
#df['new_col'] = df['col_1'].apply(f)
print (df)
             col_1  new_col
0  [A, A, A, B, C]        1
1        [D, B, C]        0
2              [C]        0
3        [A, A, A]        1
4              NaN        0

关于python - 根据 Pandas 列表列中的条件创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64063989/

相关文章:

python - Sorl-缩略图 : Clear cache of only one image?

python - 如何使用 Python Pandas 处理包含数百万条记录的 DataFrame?

python - 使用最近的行填充数据框中的缺失值

javascript - 从 node.js 运行 Python 脚本时出现 parseError

python - Django:自定义http header 身份验证

python - 使用 python 在查询内传递变量

python - 对 groupby 对象应用函数以将行附加到每个组

python - 从字典列表创建 Pandas MultiIndex 的最佳方法是什么?

Python问题: reading multiple json files from a folder load only one json

python - 使用 Python 创建 2 人游戏