我正在使用pandas(版本0.20.3)并且我希望将diff方法应用于groupby,而不是DataFrame,结果是"下划线"。
以下是代码:
import numpy as np
import pandas as pd
# creating the DataFrame
data = np.random.random(18).reshape(6,3)
indexes = ['B']*3 + ['A']*3
columns = ['x', 'y', 'z']
df = pd.DataFrame(data, index=indexes, columns=columns)
df.index.name = 'chain_id'
# Now I want to apply the diff method in function of the chain_id
df.groupby('chain_id').diff()
结果是下划线! 请注意,df.loc [' A']。diff()和df.loc [' B']。diff()返回预期的结果,所以我不明白为什么它不会与groupby合作。
答案 0 :(得分:3)
IIUC,您的错误:无法从重复的轴重新索引
df.reset_index().groupby('chain_id').diff().set_index(df.index)
Out[859]:
x y z
chain_id
B NaN NaN NaN
B -0.468771 0.192558 -0.443570
B 0.323697 0.288441 0.441060
A NaN NaN NaN
A -0.198785 0.056766 0.081513
A 0.138780 0.563841 0.635097