我有一个DataFrame如下
df=pd.DataFrame({'A':[np.nan,1,1,np.nan],'B':[2,np.nan,2,2]},index=[1,1,2,2])
df.columns=['A','A']
Run Code Online (Sandbox Code Playgroud)
现在我想ffill的值groupby的index,第一我试试
df.groupby(level=0).ffill()
Run Code Online (Sandbox Code Playgroud)
哪个返回错误代码
> ValueError: Buffer has wrong number of dimensions (expected 1, got 2)
Run Code Online (Sandbox Code Playgroud)
它看起来像个错误,然后我尝试使用apply,它将返回预期的输出。
df.groupby(level=0).apply(lambda x : x.ffill())
A A
1 NaN 2.0
1 1.0 2.0
2 1.0 2.0
2 1.0 2.0
Run Code Online (Sandbox Code Playgroud)
因为当列是唯一的参考,它的工作原理只是(Q2)的罚款,但是,创建一个索引列与列名是NaN
df.columns=['C','D']
df.groupby(level=0).ffill()
NaN C D
1 1 NaN 2.0
1 1 1.0 2.0
2 2 1.0 2.0
2 2 1.0 2.0
Run Code Online (Sandbox Code Playgroud)
问题:
1这是一个错误吗?为什么申请仍然可以在这种情况下使用?2为什么
groupby与index和一起ffill创建附加列?
它看起来肯定被窃听了。只是想指出,根据pandas 文档,该.ffill()方法是.fillna(method='ffill'). 使用后者会生成 pandas 版本中两个示例的预期输出,0.23.4而不会出现任何错误或附加列。希望有帮助。
import pandas as pd
import numpy as np
df=pd.DataFrame({'A':[np.nan,1,1,np.nan],'B':[2,np.nan,2,2]},index=[1,1,2,2])
df.columns=['A','A'] #dup column names
df.groupby(level=0).fillna(method='ffill')
Output:
A A
1 NaN 2.0
1 1.0 2.0
2 1.0 2.0
2 1.0 2.0
Run Code Online (Sandbox Code Playgroud)