Python:如何根据 if 语句的结果将元素输出到特定的列和行

标签 python excel pandas dataframe

结合excel,我正在寻找一种解决方案,可以将特定元素复制到另一个元素,具体取决于isOrganization 是否为真。使用 pandas df['isOrganization'] = df['Code'].str.endswith('000') 语句,我设法使用打印功能列出了真假结果。
如果列 isOrganization 为真,则应将为真的行从 E 和 F 列复制到 B 和 C 列。否则:该行应从 E 和 F 列复制到 D 和 E 列
IE。 :这会复制整个列 # dfo[['B', 'C']] = df[['E', 'F']] 但我只想从列中复制单行。
试图:

dfo = pd.read_excel('output.xlsx')
df = pd.read_excel('input.xls')

df['ifOrganization'] = df['Code'].str.endswith('000')

for idx, val in enumerate(df['ifOrganization']):
    if val == True:
        print(idx, val) #dfo[['B', 'C']] = df[['E', 'F']]
else:
    print(idx, val) #dfo[['D', 'E']] = df[['E', 'F']]
这是为 isOrganization 输出打印的:
Output
这是为 pf(column) 输出打印的:
Output
E和F下的前几个元素:
Element under E and F

最佳答案

使用 DataFrame.loc 通过掩码设置列,不需要将掩码转换为列。也用于匹配 False 值 ~对于反转掩码:

df = pd.read_excel('input.xls')

mask = df['Code'].str.endswith('000', na=False)

df.loc[mask, ['B', 'C']] = df.loc[mask,['F', 'G']].to_numpy()

df.loc[~mask, ['D', 'E']] = df.loc[~mask, ['F', 'G']].to_numpy()

df.to_excel('output.xlsx', index=False)
df = pd.DataFrame({
        'Code':['code000','code001','code002'] * 2,
         'B':[4,5,4,5,5,4],
         'C':[7,8,9,4,2,3],
         'D':[1,3,5,7,1,0],
         'E':[5,3,6,9,2,4],
         'F':[7,8] * 3,
         'G':[1,0] * 3
})
如果测试列名称:
print (df.columns)
Index(['Code', 'B', 'C', 'D', 'E', 'F', 'G'], dtype='object')
mask = df['Code'].str.endswith('000', na=False)

df.loc[mask, ['B', 'C']] = df.loc[mask,['F', 'G']].to_numpy()

df.loc[~mask, ['D', 'E']] = df.loc[~mask, ['F', 'G']].to_numpy()

print (df)
      Code  B  C  D  E  F  G
0  code000  7  1  1  5  7  1
1  code001  5  8  8  0  8  0
2  code002  4  9  7  1  7  1
3  code000  8  0  7  9  8  0
4  code001  5  2  7  1  7  1
5  code002  4  3  8  0  8  0

关于Python:如何根据 if 语句的结果将元素输出到特定的列和行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65087895/

相关文章:

python - 运行python脚本的不同方式

python - 设置循环条件

python - 如何将Label的bg颜色设置为无颜色(默认颜色)?

Excel 使用 INDEX 从命名范围中获取行会导致公式错误

python - scikit-learn svmlight 格式加载器中的弃用警告

vba - Excel VBA 导入 .txt 文件导致日期格式错误

excel - 在 Excel 中打开包含特殊字符的 .csv 文件

python - 带有时区的 pandas 数据框的 to_csv 错误

python - 如何使用 pandas 中的 apply 函数返回多行?

python - 如何使用 statsmodel 将截距设置为 0 - 用于多元线性回归