替换pandas中的行值

bla*_*laz 8 python numpy pandas

我想替换pandas中的行值.

例如:

import pandas as pd
import numpy as np    

a = np.array(([100, 100, 101, 101, 102, 102],
                 np.arange(6)))
pd.DataFrame(a.T)
Run Code Online (Sandbox Code Playgroud)

结果:

array([[100,   0],
       [100,   1],
       [101,   2],
       [101,   3],
       [102,   4],
       [102,   5]])
Run Code Online (Sandbox Code Playgroud)

在这里,我想用值来代替行[101, 3][200, 10],因此其结果应该是:

array([[100,   0],
       [100,   1],
       [101,   2],
       [200,  10],
       [102,   4],
       [102,   5]])
Run Code Online (Sandbox Code Playgroud)

更新

在更一般的情况下,我想替换多行.

因此,新旧行值由nx2大小的矩阵表示(n是要替换的行值的数量).例如:

old_vals = np.array(([[101, 3]],
                     [[100, 0]],
                     [[102, 5]]))

new_vals = np.array(([[200, 10]],
                     [[300, 20]],
                     [[400, 30]]))
Run Code Online (Sandbox Code Playgroud)

结果是:

array([[300,  20],
       [100,   1],
       [101,   2],
       [200,  10],
       [102,   4],
       [400,  30]])
Run Code Online (Sandbox Code Playgroud)

EdC*_*ica 8

对于单排情况:

In [35]:

df.loc[(df[0]==101) & (df[1]==3)] = [[200,10]]
df
Out[35]:
     0   1
0  100   0
1  100   1
2  101   2
3  200  10
4  102   4
5  102   5
Run Code Online (Sandbox Code Playgroud)

对于多行情况,以下内容可行:

In [60]:

a = np.array(([100, 100, 101, 101, 102, 102],
                 [0,1,3,3,3,4]))
df = pd.DataFrame(a.T)
df
Out[60]:
     0  1
0  100  0
1  100  1
2  101  3
3  101  3
4  102  3
5  102  4
In [61]:

df.loc[(df[0]==101) & (df[1]==3)] = 200,10
df
Out[61]:
     0   1
0  100   0
1  100   1
2  200  10
3  200  10
4  102   3
5  102   4
Run Code Online (Sandbox Code Playgroud)

对于多行更新,您建议以下方法可以在替换站点是单行的情况下工作,首先构造旧val的dict以进行搜索并使用新值作为替换值:

In [78]:

old_keys = [(x[0],x[1]) for x in old_vals]
new_valss = [(x[0],x[1]) for x in new_vals]
replace_vals = dict(zip(old_keys, new_vals))
replace_vals
Out[78]:
{(100, 0): array([300,  20]),
 (101, 3): array([200,  10]),
 (102, 5): array([400,  30])}
Run Code Online (Sandbox Code Playgroud)

然后我们可以遍历dict,然后使用与我的第一个答案相同的方法设置行:

In [93]:

for k,v in replace_vals.items():
    df.loc[(df[0] == k[0]) & (df[1] == k[1])] = [[v[0],v[1]]]
df
     0  1
0  100  0
     0  1
5  102  5
     0  1
3  101  3
Out[93]:
     0   1
0  300  20
1  100   1
2  101   2
3  200  10
4  102   4
5  400  30
Run Code Online (Sandbox Code Playgroud)


ale*_*inn 6

最简单的方法应该是这样的:

df.loc[[3],0:1] = 200,10
Run Code Online (Sandbox Code Playgroud)

在本例中,3 是数据帧的第三行,而 0 和 1 是列。

相反,此代码允许您迭代每一行,检查其内容并将其替换为您想要的内容。

target = [101,3]
mod = [200,10]

for index, row in df.iterrows():
    if row[0] == target[0] and row[1] == target[1]:
        row[0] = mod[0]
        row[1] = mod[1]

print(df)
Run Code Online (Sandbox Code Playgroud)