Python / Pandas - 更新一组记录的数据

时间:2016-03-19 21:24:19

标签: python pandas dataframe

我正在尝试更新一些数据,但我需要更新的数据是我需要用来选择唯一记录的列的一部分。

import pandas as pd

data = [{'subid':'123','grade':'K'},{'subid':'123','grade':'3rd'}, {'subid':'123','grade':'6th'}, {'subid':'456','grade':'1st'},{'subid':'456','grade':'3rd'},{'subid':'456','grade':'5th'}]
df = pd.DataFrame(data)
df

我正在尝试使用str.replace

df['grade'][df['subid']== '456'].str.replace('3rd','4th')

我得到以下内容,但无法更新df。

3  1st
4  4th
5  5th
Name: grade, dtype: object

df
  grade     subid
0   K       123
1   3rd     123
2   6th     123
3   1st     456
4   3rd     456
5   5th     456

尝试将以下内容作为最终df

  grade     subid
 0  K       123
 1  3rd     123
 2  6th     123
 3  1st     456
 4  4th     456
 5  5th     456

有更好的更新方法吗?

2 个答案:

答案 0 :(得分:3)

试试这个:

In [138]: df.loc[df['subid']== '456', 'grade'] = df.grade.replace({'3rd':'4th'})

In [139]: df
Out[139]:
  grade subid
0     K   123
1   3rd   123
2   6th   123
3   1st   456
4   4th   456
5   5th   456

答案 1 :(得分:1)

您可以使用更复杂的行选择和赋值运算符来执行此操作:

scriptDataProto.foo = function() {
    alert('Hello world!');
};
var scriptData = document.registerElement('script-data', {
    prototype: scriptDataProto
});
var element = new scriptData();
element.foo(); // alerts "Hello world!"
document.body.appendChild(element);
element.onclick = element.foo;

打印出来:

#!/usr/bin/python

import pandas as pd

data = [{'subid':'123','grade':'K'},{'subid':'123','grade':'3rd'}, {'subid':'123','grade':'6th'}, {'subid':'456','grade':'1st'},{'subid':'456','grade':'3rd'},{'subid':'456','grade':'5th'}]
df = pd.DataFrame(data)
print df

df['grade'][(df['subid']== '456') & (df['grade'] == '3rd')] = '4th'
print df