简体   繁体   English

Python - Pandas - Dataframe 如何在使用.count时将变量添加到列

[英]Python - Pandas - Dataframe How to add variables to a column when using .count

I am creating a new column that will count all ids but exclude a few rows of customers where the customer's ID has a certain prefix and has no repeat orders我正在创建一个新列,该列将计算所有 ID,但排除几行客户 ID 具有特定前缀且没有重复订单的客户

df['newcolumn'] = df[(df.notnull['Date']) & (df['ID'].str.contains('prefix')) & (df['Repeat order'] == 'No')].groupby(['ID'], as_index=False).count()

I am getting below error我得到以下错误

TypeError: 'method' object is not subscriptable

Still no difference when I replaced [] with () to resolve above error当我用 () 替换 [] 来解决上述错误时仍然没有区别

I also replaced df[(df['Date'].notnull) and got TypeError: unsupported operand type(s) for &: 'method' and 'bool' error我还替换了df[(df['Date'].notnull)并得到TypeError: unsupported operand type(s) for &: 'method' and 'bool' error

This is the coding equivalence of run-on sentence during English class.这是英文class期间连贯句的编码等价。 You were trying to stuff so many things into a single line that it's hard to tell where the problem is.您试图将这么多东西塞进一行,以至于很难说出问题出在哪里。

Break up you code:分解你的代码:

cond = (
  df['Date'].notnull()
  & df['ID'].str.contains('prefix')
  & df['Repeat order'].eq('No')
)
df['newcolumn'] = df[cond].groupby(['ID'], as_index=False).count()

NB: your original error was because of this:注意:你原来的错误是因为这个:

df.notnull['Date']

df.notnull is a method. df.notnull是一种方法。 It's not subscriptable.它不可下标。 You can execute the method and subscript the result:您可以执行该方法并对结果下标:

df.notnull()['Date']

or you can extract a column from the data frame and run notnull on it:或者您可以从数据框中提取一列并在其上运行notnull

df['Date'].notnull()

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

相关问题 Python - Pandas - Dataframe 如何在使用.count时将notnull添加到列 - Python - Pandas - Dataframe How to add notnull to a column when using .count Python将列添加到Pandas Dataframe,这是另一列中的列表元素计数 - Python Add Column to Pandas Dataframe That is a Count of List Elements in Another Column 使用 python pandas 中的循环向 dataframe 添加一列 - add a column to the dataframe using a loop in python pandas Pandas (python):如何将列添加到数据帧以进行索引? - Pandas (python): How to add column to dataframe for index? 将列添加到 python pandas 中的数据帧 - add column to a dataframe in python pandas 当列中的字符串计数最大时,Pandas 使用 groupby 转换数据帧 - Pandas transform dataframe using groupby when count of a string in a column is maximum 如何为 pandas dataframe 中的新列或 python 上的值计数设置参数? - How to set parameters for new column in pandas dataframe OR for a value count on python? 将重复计数列添加到熊猫数据框 - Add repeat count column to a pandas dataframe 在熊猫数据框中添加指示计数的新列 - Add new column indicating count in a pandas dataframe 使用 python pandas dataframe.to_html() 时是否可以将 class 或 id 添加到特定列 - Is it possible to add a class or id to a specific column <td> when using python pandas dataframe.to_html()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM