Sea*_*thy 3 python apply pandas
我想在 pandas 中创建一个简单的计数器,每次循环完成时该计数器都会加一。这应该很简单,但我无法弄清楚...这是我想做的,并带有说明性的 pandas DataFrame:
# Illustrative dataframe
df = pd.DataFrame({'a':[0,0,1,1,0,0,1,1], 'b':[0,1,1,0,0,1,1,0]})
# Initialize counter to zero
counter = 0
# Increment the counter by 1 every time 'a' == 1 and 'b' == 0
df['c'] = [counter += 1 if (df['a'] == 1) and (df['b'] == 0)]
Run Code Online (Sandbox Code Playgroud)
如果有人向我展示如何使用 pandas.apply 使用自定义函数来执行此操作,我会很高兴。本质上,我循环遍历 DataFrame 中的每个记录/行,并比较两列。
我知道我可能可以使用 numpy.where() 来做到这一点,然后进行扩展总和,但我真的很想学习如何将 apply 与自定义函数一起使用。
这是我尝试的另一种方法,使用自定义函数和 pandas.apply:
counter_list = []
counter = 0
def count_cycles(df):
if (df['a'] == 1) and (df['b'] == 0):
counter += 1
counter_list.append(counter)
return pd.Series(counter_list)
df['c'] = df.apply(count_cycles)
Run Code Online (Sandbox Code Playgroud)
你可以通过以下方式实现你想要的
df['c'] = ((df['a'] == 1) & (df['b'] == 0)).cumsum()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
906 次 |
| 最近记录: |