如何计算python熊猫中的特定单元格值?

时间:2019-08-30 17:54:17

标签: python python-3.x pandas calculated-columns

有一个熊猫数据框,如下所示:

import pandas as pd
raw_data = {'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'],
'age': [20, 19, 22, 21],
'favorite_color': ['blue', 'blue', 'yellow', "green"],
'grade': [88, 92, 95, 70]}

df = pd.DataFrame(raw_data)

我想将age列中等于grade的{​​{1}}和blue数字单元格值除以125.0值,而favorite_color值除以130.0和{{ 1}}至135.0。结果将插入到新列yellowgreen中。 通过下面的代码,我收到错误。

age_new

错误:

grade_new

2 个答案:

答案 0 :(得分:4)

map

mods = {'blue': 125, 'yellow': 130, 'green': 135}

df.assign(
    mods=df.favorite_color.map(mods),
    age_new=lambda d: d.age / d.mods,
    grade_new=lambda d: d.grade / d.mods
)

               name  age favorite_color  grade  mods   age_new  grade_new
0    Willard Morris   20           blue     88   125  0.160000   0.704000
1       Al Jennings   19           blue     92   125  0.152000   0.736000
2      Omar Mullins   22         yellow     95   130  0.169231   0.730769
3  Spencer McDaniel   21          green     70   135  0.155556   0.518519

类似

mods = {'blue': 125, 'yellow': 130, 'green': 135}

df.join(df[['age', 'grade']].div(df.favorite_color.map(mods), axis=0).add_suffix('_new'))

               name  age favorite_color  grade   age_new  grade_new
0    Willard Morris   20           blue     88  0.160000   0.704000
1       Al Jennings   19           blue     92  0.152000   0.736000
2      Omar Mullins   22         yellow     95  0.169231   0.730769
3  Spencer McDaniel   21          green     70  0.155556   0.518519

答案 1 :(得分:2)

您可以使用import { Component, OnInit } from '@angular/core'; import { Store, select } from '@ngrx/store'; import { Observable } from 'rxjs'; import { increment, decrement, reset } from '../stateMan/actions/counter.actions'; import TodoItem from '../../models/TodoItem' interface IStore { count: number, todo: { data : number } } @Component({ selector: 'app-counter', templateUrl: './counter.component.html', styleUrls: ['./counter.component.scss'] }) export class CounterComponent implements OnInit { count$: Observable<number>; todoData$: Observable<any>; constructor(private store: Store<IStore>) { this.count$ = store.select('count'); this.todoData$ = store.select('todo'); } `//////// HOW?????? increment() { // How do I get this.todoData$.data???? console.log('show todo data', this.todoData$.data) } } 代替.replace,这样您只需执行一次操作即可。

.loc

哪个给

import pandas as pd

raw_data = {
    'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'],
    'age': [20, 19, 22, 21],
    'favorite_color': ['blue', 'blue', 'yellow', "green"],
    'grade': [88, 92, 95, 70]}

df = pd.DataFrame(raw_data)

color_d = {
    "blue": 125,
    "yellow": 130,
    "green": 135
}

df[["age_new", "grade_new"]] = df[["age", "grade"]].div(
    df['favorite_color'].replace(color_d), 
    axis=0)

df.head()