请问我的语句都有哪些错误?

我想实现一个Excel表里,当sales org为2118是,判断符合条件的行数占总行数的%。

img

data['Sales Org'] 获取到的是一列数据

所以判断的时候可以用

count = 0
for sale in data['Sales Org']:
    if sale == '2118':
        count= count+1
print("百分比为:{:.2f}%" .format (count * 100 / (x * 1.0)))

发一下完整代码(可以删去具体地址用123.csv代替)和报错信息看看?

import pandas as pd

a = pd.read_excel('123.xlsx')
print(len(a[a['c'] == 2])/len(a))

大概这种感觉,直接用条件切片除以纵切片即可,其中c代表待统计的column名称,2代表要统计的关键字,在你的情况下为2118(也可能是'2118'字符串)
有帮助望采纳


import pandas as pd
import openpyxl
data=  pd.read_excel('123.xlsx',sheet_name='details')
x=len(data)
if data['Sale Org'] is'2118':
     df_bool_multi_and = ((data['SDV Code'] != 'LP6') & (data['Block Bucket (Aged update)'] != 'Service')&(data['Aged'] == 'Aged order'))
     print(df_bool_multi_and.sum()/x)
else:
     df_list=pd.DataFrame({'Sales Order Type':['ZB1S','ZB1B','ZB1A','ZB1O','ZB4S','ZB4B']})
     df_bool_multi_and2 = ((data['SDV Code'] != 'LP6') & (data['Block Bucket (Aged update)'] != 'Service') & (data['Aged'] == 'Aged order') & (data['Blue Aged Excl. Flag'] != 'Y') & (data['Sales Order Type'] in df_list))
     print(df_bool_multi_and2.sum()/x)

报错信息:
"C:\Program Files\Python39\python.exe" "123.py"
123.py:5: SyntaxWarning: "is" with a literal. Did you mean "=="?
if data['Sale Org'] is'2118':

Traceback (most recent call last):
File "123.py", line 3361, in get_loc
return self._engine.get_loc(casted_key)
File "pandas_libs\index.pyx", line 76, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libs\index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libs\hashtable_class_helper.pxi", line 5198, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas_libs\hashtable_class_helper.pxi", line 5206, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Sale Org'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "123.py", line 5, in
if data['Sale Org'] is'2118':
File "C:\Program Files\Python39\lib\site-packages\pandas\core\frame.py", line 3455, in getitem
indexer = self.columns.get_loc(key)
File "C:\Program Files\Python39\lib\site-packages\pandas\core\indexes\base.py", line 3363, in get_loc
raise KeyError(key) from err
KeyError: 'Sale Org'

Process finished with exit code 1