2
A
回答
2
使用倒置,即乘difference
的地方是mul
必要多的所有行:
cols = df.index.difference(['Revenue'])
df.loc[cols] = df.loc[cols].mul(-1)
样品:
df = pd.DataFrame({'A':[1,2,3],
'B':[-4,5,6],
'C':[7,-8,9],
'D':[1,3,-5],
'E':[5,-3,6],
'F':[-7,4,3]},
index=['Revenue', 'Direct Cost','Manpower'])
print (df)
A B C D E F
Revenue 1 -4 7 1 5 -7
Direct Cost 2 5 -8 3 -3 4
Manpower 3 6 9 -5 6 3
cols = df.index.difference(['Revenue'])
df.loc[cols] = df.loc[cols].mul(-1)
print (df)
A B C D E F
Revenue 1 -4 7 1 5 -7
Direct Cost -2 -5 8 -3 3 -4
Manpower -3 -6 -9 5 -6 -3
另一种解决方案是创建Series
多个与to_series
+ map
:
s = (df.index.to_series() == 'Revenue').map({True:1, False:-1})
print (s)
Revenue 1
Direct Cost -1
Manpower -1
dtype: int64
df = df.mul(s, axis=0)
print (df)
A B C D E F
Revenue 1 -4 7 1 5 -7
Direct Cost -2 -5 8 -3 3 -4
Manpower -3 -6 -9 5 -6 -3
或者simplier使用numpy.where
用于转换阵列通过掩模mul
:
df = df.mul(np.where(df.index == 'Revenue', 1, -1), axis=0)
print (df)
A B C D E F
Revenue 1 -4 7 1 5 -7
Direct Cost -2 -5 8 -3 3 -4
Manpower -3 -6 -9 5 -6 -3
1
使用@ jezrael的设置
df = pd.DataFrame({'A':[1,2,3],
'B':[-4,5,6],
'C':[7,-8,9],
'D':[1,3,-5],
'E':[5,-3,6],
'F':[-7,4,3]},
index=['Revenue', 'Direct Cost','Manpower'])
构建的-1
/+1
从布尔数组的数组。直接在底层values
阵列上操作。这非常快。
当索引值是Revenue
时,我们得到一个True
,否则False
。乘上2
,我们得到2
时等于Revenue
,否则0
。减去1
我们得到1
时Revenue
否则-1
。现在我们只需要将这个乘以values数组中的每一列。我们使用numpy广播。为了播出,我们把的-1
和1
我们的一维数组到的N×1个阵列[:, None]
。现在我们可以乘以每一列。
df.values[:] *= ((df.index.values == 'Revenue') * 2 - 1)[:, None]
df
A B C D E F
Revenue 1 -4 7 1 5 -7
Direct Cost -2 -5 8 -3 3 -4
Manpower -3 -6 -9 5 -6 -3
相关问题
- 1. 熊猫选择未对齐的索引
- 2. Python - 熊猫索引
- 3. 熊猫得到索引系列的“索引”标签
- 4. 熊猫列索引搜索?
- 5. 熊猫索引.loc错误“'标签[2013_09_09]不在[索引]'”
- 6. 用熊猫分级索引
- 7. 熊猫摘要索引
- 8. 熊猫DataFrame.groupby包括索引
- 9. 熊猫索引isin方法
- 10. 熊猫上索引列
- 11. 熊猫索引编组后
- 12. 重置列索引熊猫?
- 13. 熊猫多级索引行
- 14. 熊猫索引跳过值
- 15. 熊猫:基于索引
- 16. 熊猫中的逻辑多元索引
- 17. 熊猫中的多重索引
- 18. 熊猫的熊猫(v0.8.0)的高级索引分配
- 19. 在熊猫中剥离索引值
- 20. 检索熊猫数据框列索引
- 21. Python的熊猫 - 基于索引
- 22. Python的大熊猫to_json索引格式
- 23. 熊猫 - 索引类型值的更改
- 24. 如何获得熊猫的行索引?
- 25. IndexError:索引超出熊猫的范围
- 26. 对熊猫重复索引的操作
- 27. 在熊猫中选择时忽略重复索引
- 28. 熊猫DataFrame索引的自动增量选项
- 29. 熊猫:调用df.loc []选自pd.datetime的索引
- 30. 熊猫非索引过滤器的索引过滤器
这个作品很好,谢谢!使用最后一个,因为它是最简单的 – idazuwaika
很高兴可以帮助,最后是最好的;)美好的周末! – jezrael