简体   繁体   English

遍历列 pandas dataframe 并根据条件创建另一列

[英]iterate through columns pandas dataframe and create another column based on a condition

I have a dataframe df我有一个 dataframe df

ID  ID2 escto1 escto2   escto3
1   A   1   0   0
2   B   0   1   0
3   C   0   0   3
4   D   0   2   0

so either using indexing or using wildcard所以要么使用索引要么使用通配符

like column name 'escto*'
if df.iloc[:, 2:]>0 then df.helper=1

or或者

df.loc[(df.iloc[:, 3:]>0,'Transfer')]=1

So that output becomes这样 output 就变成了

ID  ID2 escto1  escto2  escto3  helper
1   A   1   0   0   1
2   B   0   1   0   1
3   C   0   0   3   1
4   D   0   2   0   1

Output Output

One option is to use the boolean output:一种选择是使用 boolean output:

df.assign(helper = df.filter(like='escto').gt(0).any(1).astype(int))

   ID ID2  escto1  escto2  escto3  helper
0   1   A       1       0       0       1
1   2   B       0       1       0       1
2   3   C       0       0       3       1
3   4   D       0       2       0       1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 pandas dataframe 列上迭代并根据条件创建一个新列 - Iterate on a pandas dataframe column and create a new column based on condition Pandas 根据来自另一个 dataframe 的计数和条件创建新列 - Pandas Create new column based on a count and a condition from another dataframe Pandas 数据框根据另一列的条件创建新行 - Pandas dataframe create new rows based on condition from another column 遍历 pandas dataframe 的列并为循环中的每个选定列创建一个新的 dataframe - Iterate through columns of pandas dataframe and create a new dataframe for each selected column in a loop 迭代数据框的两列并根据另一列的条件替换空值 - Iterate over two columns of a dataframe and replace null values based on condition of another column 根据 dataframe 查询条件在 Pandas 中创建列 - Create column in Pandas based on dataframe query condition 根据条件在pandas数据框中创建列 - Create column in pandas dataframe based on condition 根据另一列的条件创建pandas列 - Create pandas column based on condition of another column 使用基于列范围的条件创建 pandas 列 - Create pandas column with a condition based on a range of columns 检查特定列是否大于另一列并根据 pandas dataframe 中的条件创建新列 - Check if specific column is greater than another column and create a new column based on condition in pandas dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM