English 中文(简体)
Pandas数据框架:如何通过使用其浏览指数来增加具体价值?
原标题:Pandas dataframe: how to multiply a specific value by using its row index?

我想改变潘达斯数据框架中的具体价值。 这里是一个实例数据框架(在现实中,还有许多方面):

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

在这里,我想将“10.90979”乘以“代码>10在“<1>上加标签。 我不想写“10.90979 * 10”,因为我只知道我拥有一个称为“(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)

然而,这给我带来了令人ir慕的产出。 我收到了:

              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 Depende mul .

谁能向我指出正确的方向?

问题回答

你的问题是,由于<代码> CH4 <代码>Value栏的数值,该栏的数值在你试图乘数时作为指示处理;

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

你们需要将价值转换为浮动值,以进行操作。 请注意:booleanindexing, 查阅所有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)

<><><>>>>

http://www.un.org/Depts/DGACM/index_spanish.htm

cond = df[ Property ].eq( Density (g/cm3) )
df.assign(Value=df[ Value ].where(cond).astype( float ).mul(10).fillna(df[ Value ]))

注:

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

www.un.org/Depts/DGACM/index_spanish.htm 例

import pandas as pd
data1 = { Value : [ CH4 ,  -10.90979 ,  5.00000 ], 
          Property : [ Type ,  Density (g/cm3) ,  Temperature (K) ]}
df = pd.DataFrame(data1)

正如其他人指出的,你的<代码>Value栏不是数字(由于<代码>CH4第一数值)。 但更根本的是,你为什么想要将密度乘以<条码>10<>/代码>? 问题越高?

From this question (and your previous one, now deleted), it looks like you have chemical compounds and are trying to do unit conversions on their physical properties. I would recommend looking into packages that do that readily. For example: pint and its pandas companion pint_pandas.

看来,您的化学化合物(例如, CH4 )的数据Frams作为第一行的价值,然后是一些物理特性。

You may be better off using dicts to represent your properties. E.g.:

from pint import UnitRegistry

Q_ = UnitRegistry().Quantity

compounds = {
     CH4 : dict(
        name= methane ,
        molar_mass=Q_(16.043,  g / mol ),
        density_0=Q_(0.657,  kg/m**3 ),
        at_0=Q_(25,  °C ),
        density_1=Q_(0.717,  kg/m**3 ),
        at_1=Q_(0,  °C ),
        density_2=Q_(422.8,  g/L ),
        at_2=Q_(-162,  °C ),
    ),
     SO2 : dict(
        name= sulfur dioxide ,
        molar_mass=Q_(64.066,  g / mol ),
        density_0=Q_(2.6288,  kg / m**3 ),
        at_0=Q_(25,  °C ),
    ),
}

然后,如果你愿意的话,你可以将此转化为数据框架:

import pandas as pd
import pint_pandas

df = pd.DataFrame(compounds).T

将一栏具体改为某些理想的单位,例如:

>>> df[ density_0 ].astype( pint[g/L] )
CH4    0.6570000000000001
SO2    2.6288000000000005

a. 整个数据基

z = df.astype(dict(
    molar_mass= pint[g/mol] ,
    density_0= pint[g/L] ,
    density_1= pint[g/L] ,
    density_2= pint[g/L] ,
    at_0= pint[degC] ,
    at_1= pint[degC] ,
    at_2= pint[degC] ,
))

>>> z
               name  molar_mass           density_0  at_0           density_1  at_1  density_2  at_2
CH4         methane      16.043  0.6570000000000001    25  0.7170000000000001     0      422.8  -162
SO2  sulfur dioxide      64.066  2.6288000000000005    25                 nan   nan        nan   nan

>>> z.dtypes
name                        object
molar_mass       pint[gram / mole]
density_0       pint[gram / liter]
at_0          pint[degree_Celsius]
density_1       pint[gram / liter]
at_1          pint[degree_Celsius]
density_2       pint[gram / liter]
at_2          pint[degree_Celsius]
dtype: object




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...