python中是否有一个函数可以帮助我将所有值关联在一行中,而不是多行中



我想在同一行上顶部显示该数据帧中每年的值。与2019年一样,我只希望2019年有一行具有所有相应的值。

在此处输入图像描述

Year    Profits of A    Profits of B    Profits of C    Profits of D    Profits of E
0   1999    200.0   NaN NaN NaN NaN
1   2000    220.0   NaN NaN NaN NaN
2   2001    240.0   NaN NaN NaN NaN
3   2002    260.0   NaN NaN NaN NaN
4   2003    224.0   NaN NaN NaN NaN
... ... ... ... ... ... ...
58  2018    NaN NaN NaN NaN 123.25
59  2019    NaN 157.5   NaN NaN NaN
60  2019    NaN NaN 99.0    NaN NaN
61  2019    NaN NaN NaN 82.8    NaN
62  2019    NaN NaN NaN NaN 102.00

您可以只按年份分组并求和:

import pandas as pd
import io
data = io.StringIO(
"""Index    Year    "Profits of A"    "Profits of B"    "Profits of C"    "Profits of D"    "Profits of E"
0   1999    200.0   NaN NaN NaN NaN
1   2000    220.0   NaN NaN NaN NaN
2   2001    240.0   NaN NaN NaN NaN
3   2002    260.0   NaN NaN NaN NaN
4   2003    224.0   NaN NaN NaN NaN
58  2018    NaN NaN NaN NaN 123.25
59  2019    NaN 157.5   NaN NaN NaN
60  2019    NaN NaN 99.0    NaN NaN
61  2019    NaN NaN NaN 82.8    NaN
62  2019    NaN NaN NaN NaN 102.00""")
df = pd.read_table(data, index_col=0, delim_whitespace=True)
df2 = df.groupby('Year').sum().reset_index()
print(df2)
#    Year  Profits of A  Profits of B  Profits of C  Profits of D  Profits of E
# 0  1999         200.0           0.0           0.0           0.0          0.00
# 1  2000         220.0           0.0           0.0           0.0          0.00
# 2  2001         240.0           0.0           0.0           0.0          0.00
# 3  2002         260.0           0.0           0.0           0.0          0.00
# 4  2003         224.0           0.0           0.0           0.0          0.00
# 5  2018           0.0           0.0           0.0           0.0        123.25
# 6  2019           0.0         157.5          99.0          82.8        102.00

使用此:

x3.groupby('Year').max()

假设每年每列只有一个非零值

最新更新