Pandas 数据框:如何使用其行索引来乘以特定值?

问题描述 投票:0回答:1

我想更改 Pandas 数据框中的特定值。这是一个示例数据框(实际上,还有更多行):

              Value                       Property
0               CH4                       Type
1          -10.90979                      Density (g/cm3)
2           5.00000                       Temperature (K)

这里我想将标记为“

10.90979
”的行中的“
10
”乘以
1
。我不想写“
10.90979 * 10
”,因为我只知道我有一个名为“
Density (g/cm3)
”的属性。我不知道它的价值。所以我想使用乘法中出现“
Density (g/cm3)
”的行的索引。

我已经尝试过:

row_index = df.index.get_loc(df[df['Property'] == 'Density (g/cm3)'].index[0])
new_value = df.iloc[row_index][0] * 10
df["Value"].replace(df.iloc[row_index][0], new_value, inplace=True)

但是,这给了我奇怪的输出。我得到:

              Value                       Property
0               CH4                       Type
1 -10.90979-10.90979...                   Density (g/cm3)
2           5.00000                       Temperature (K)

我无法发布代码的详细信息,但希望有人能认识到一个简单的错误。我不确定我是否正确地对数据框使用了乘法。我也尝试过使用

df.iloc[row_index][0].mul(10)

但出现错误

AttributeError: 'str' object has no attribute 'mul'

有人可以指出我正确的方向吗?

python python-3.x pandas dataframe replace
1个回答
0
投票

您的问题是,由于

CH4
列中的
Value
值,当您尝试将它们相乘时,该列中的值将被视为字符串;因此

'-10.90979'*10 = '-10.90979-10.90979-10.90979...'

您需要将值转换为浮点数才能对其进行操作。请注意,您可以使用 布尔索引 来访问所有

Density
值:

mask = df['Property'] == 'Density (g/cm3)'
df.loc[mask, 'Value'] = df.loc[mask, 'Value'].astype(float) * 10

输出:

      Value         Property
0       CH4             Type
1 -109.0979  Density (g/cm3)
2   5.00000  Temperature (K)
© www.soinside.com 2019 - 2024. All rights reserved.