我有以下PandasDataFrame:
df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
"bar", "bar", "bar", "bar",'foo' ],
"B": ["one", "one", "one", "two", "two",
"one", "one", "two", "two", 'two'],
"C": ["small", "large", "large", "small",
"small", "large", "small", "small",
"large", 'large'],
"D": [1, 2, 2, 3, 3, 4, 5, 6, 7,8],
})
输出如下:
print(df)
A B C D
0 foo one small 1
1 foo one large 2
2 foo one large 2
3 foo two small 3
4 foo two small 3
5 bar one large 4
6 bar one small 5
7 bar two small 6
8 bar two large 7
9 foo two large 8
那么我将按如下方式创建透视表:
table = pd.pivot_table(df, values='D', index=['A'],
columns=['B','C'])
输出如下:
print(table)
B one two
C large small large small
A
bar 4 5 7 6
foo 2 1 8 3
如何将large
和small
之间的差值(large
-small
)相加以得到one
和two
(下表中的diff
)?
B one two
C large small diff large small difff
A
bar 4 5 -1 7 6 1
foo 2 1 1 8 3 5
我看到了一些以前的答案,但只处理了1列。此外,理想情况下,将使用aggfunc
完成
此外,如何将表格重新转换为初始格式?预期输出为:
A B C D
0 foo one small 1
1 foo one large 2
2 foo one large 2
3 foo two small 3
4 foo two small 3
5 bar one large 4
6 bar one small 5
7 bar two small 6
8 bar two large 7
9 foo two large 8
10 bar one diff -1
11 bar two diff 1
12 foo one diff 1
13 foo two diff 5
提前感谢您的帮助!
1条答案
按热度按时间hc2pp10m1#
得到