私信  •  关注

Arne

Arne 最近创建的主题
Arne 最近回复了
3 年前
回复了 Arne 创建的主题 » 如何使用python按顺序映射销售和购买?

如果您只对每个项目的最终余额值感兴趣,这里有一种快速计算方法:

添加另外两列,其中包含与相同的绝对值 Qty Value ,但在 Code 价值是 Sell 。然后你可以按项目分组,并对每个项目的这些值求和,以得到剩余的项目数和余额。

sale = df.Code == 'Sell'

df['Qty_signed'] = df.Qty.copy()
df.loc[sale, 'Qty_signed'] *= -1 

df['Value_signed'] = df.Value.copy()
df.loc[sale, 'Value_signed'] *= -1 

qty_remaining = df.groupby('Item')['Qty_signed'].sum()
print(qty_remaining)

money_spent = df.groupby('Item')['Value_signed'].sum()
print(money_spent)

输出:

Item
A    11
Name: Qty_signed, dtype: int64
Item
A    995.0
Name: Value_signed, dtype: float64

首先是 == True 是多余的,但这与错误无关。

该错误表明,对于其中一个变量名 i (顺便说一句,这有点误导,因为 通常是这样一个循环中的整数。)表情 est2.pvalues[i] 是一个熊猫系列,而不仅仅是一个值。如果看不到有问题的变量名,就不可能知道为什么会发生这种情况。

无论如何, est2.pvalues 是一个熊猫系列,因此您可以通过如下布尔索引获得所有低p值(以及相应的变量名):

est2.pvalues[est2.pvalues < 0.05]
6 年前
回复了 Arne 创建的主题 » Python:如何使用regex显示文本文件中的前几个数字

提取排序条件

首先,你需要得到你想要对每一行进行排序的信息。 可以使用此正则表达式从行中提取视图和路径:

>>> import re
>>> criteria_re = re.compile(r'file (?P<path>\S*) (?P<views>\d*) \d*')
>>> m = criteria_re.match('file GameOfThrones 900 0')
>>> res = (int(m.group('views')), m.group('path'))
>>> res
(900, 'GameOfThrones')

排序

现在整个过程只需要应用到您的文件集合。因为我们不需要默认搜索,所以需要设置 key 搜索函数的参数,帮助它知道我们到底要按什么排序:

def sort_files(files):
    lines = []
    for file in records:
        for line in open(file):
            m = criteria_re.match(line)
            # maybe do some error handling here, in case the regex doesn't match
            lines.append((line, (-int(m.group('views')), m.group('path'))))
            # taking the negative view count makes the comparison later a
            # bit more simple, since we can just sort be descending order
            # for both view as well as alphabetical path order 
    # the sorting criteria were only tagging along to help with the order, so
    # we can discard them in the result
    return [line for line, criterion in sorted(lines, key=lambda x: x[1])]
6 年前
回复了 Arne 创建的主题 » 如果用户输入字符串为空、数字或具有非ASCII python

如果您熟悉正则表达式,可以按以下方式测试条件“不得为空”和“不得包含数字”:

import re

# match one or more characters that range from a to z or A to Z
username_check = re.compile(r'[a-zA-Z]+')

...
while True:
  if rsp == 'y':
    f_name = input('Enter first name: ')
    while not username_check.fullmatch(f_name):
      print('First name cannot be empty or have numeric values')
      f_name = input('Enter first name: ')

正则表达式的好处在于,您可以非常灵活地扩展当前的最小解决方案,以测试非常特定的模式:

import re

# allow unicode word characters
allowed = re.compile(r'\w+')
# numbers are still not allowed
forbidden = re.compile(r'\d')

while True:
    f_name = input('Enter first name: ')
    while not (allowed.fullmatch(f_name) and not forbidden.search(f_name)):
      print('First name cannot be empty or have numeric values')
      f_name = input('Enter first name: ')