pandas 数据框中的行除以它们的列总和
Row divide by their column sum in pandas dataframe
我正在尝试将行值除以它们的列总和。我想我可以一行一行地做,然后将它们连接在一起,但我想知道在 pandas.
中是否有更有效的方法来做到这一点
abc = {
'fruits': {0: 'apple', 1: 'orange', 2: 'total'},
'Monday': {0: 2, 1: 4, 2: 6},
'Tuesday': {0: -2, 1: -6, 2: -8},
'Wednesday': {0: -40, 1: -65, 2: -105}
}
pd.DataFrame.from_dict(abc)
fruits Monday Tuesday Wednesday
0 apple 2 -2 -40
1 orange 4 -6 -65
2 total 6 -8 -105
预期输出:
fruits Monday Tuesday Wednesday
0 apple 0.33 0.25 0.38
1 orange 0.67 0.75 0.62
df = pd.DataFrame.from_dict(abc)
df.iloc[:,1:] = df.iloc[:,1:] / df.iloc[-1,1:]
df = df[:-1]
df
df.iloc[:,1:]
获取除 fruits 之外的所有列。 df.iloc[-1,1:]
是数据帧的最后一行,总共是 。 df = df[:-1]
将除 total 行之外的所有行分配为 df
我正在尝试将行值除以它们的列总和。我想我可以一行一行地做,然后将它们连接在一起,但我想知道在 pandas.
中是否有更有效的方法来做到这一点abc = {
'fruits': {0: 'apple', 1: 'orange', 2: 'total'},
'Monday': {0: 2, 1: 4, 2: 6},
'Tuesday': {0: -2, 1: -6, 2: -8},
'Wednesday': {0: -40, 1: -65, 2: -105}
}
pd.DataFrame.from_dict(abc)
fruits Monday Tuesday Wednesday
0 apple 2 -2 -40
1 orange 4 -6 -65
2 total 6 -8 -105
预期输出:
fruits Monday Tuesday Wednesday
0 apple 0.33 0.25 0.38
1 orange 0.67 0.75 0.62
df = pd.DataFrame.from_dict(abc)
df.iloc[:,1:] = df.iloc[:,1:] / df.iloc[-1,1:]
df = df[:-1]
df
df.iloc[:,1:]
获取除 fruits 之外的所有列。 df.iloc[-1,1:]
是数据帧的最后一行,总共是 。 df = df[:-1]
将除 total 行之外的所有行分配为 df