python - 根据 pandas 中的情况替换某些值

标签 python pandas dataframe replace

我正在尝试将以下 R 代码转换为 Python,但由于行索引而陷入困境......

df$col3[index+1] <− df$col2[index] # what he want :col2 in certain index  assign its value to col3 by index increment 1.

虚构示例

df = pd.DataFrame({'id' : [1, 1, 1, 2, 2, 3, 4, 4, 4, 4, 5, 5], 
'id_old' : [1, 1, 2, 2, 3, 4, 4, 4, 4, 5, 5, 5], 
'col1' : np.random.normal(size = 12), 
'col2' : np.random.randint(low = 20, high = 50, size = 12), 
'col3' : np.repeat(20, 12)})
print(df)

myindex = np.where(df.id != df.id_old) # tuple
print(myindex)
print(np.add(myindex, 1))
replacement_values = df.iloc[myindex][['col2']]

输出

    id  id_old      col1  col2  col3
0    1       1  0.308380    23    20
1    1       1  1.185646    35    20
2    1       2 -0.432066    27    20
3    2       2  0.115055    32    20
4    2       3  0.683291    34    20
5    3       4 -1.916321    42    20
6    4       4  0.888327    34    20
7    4       4  1.312879    29    20
8    4       4  1.260612    27    20
9    4       5  0.062635    22    20
10   5       5  0.081149    23    20
11   5       5 -1.872873    32    20

(array([2, 4, 5, 9]),)
[[ 3  5  6 10]]

这是我尝试过的:

df.loc[np.add(myindex, 1), 'col3'] = replacement_values
df.loc[df.index.isin(np.add(myindex + 1)), 'col3'] = replacement_values

期望的结果:

    id  id_old      col1  col2  col3
0    1       1  0.308380    23    20
1    1       1  1.185646    35    20
2    1       2 -0.432066    27    20
3    2       2  0.115055    32    27
4    2       3  0.683291    34    20
5    3       4 -1.916321    42    34
6    4       4  0.888327    34    42
7    4       4  1.312879    29    20
8    4       4  1.260612    27    20
9    4       5  0.062635    22    20
10   5       5  0.081149    23    22
11   5       5 -1.872873    32    20

我想我忽略了一些基本的东西,或者我完全走错了路?

非常感谢您的帮助!

最佳答案

通过添加values来修复您的代码 R 中的 data.frame 对索引不敏感,但在 pandas 中> ,索引很重要

df=pd.read_clipboard()
df.loc[np.add(myindex, 1)[0],'col3']=df.iloc[myindex]['col2'].values
df
Out[399]: 
    id  id_old      col1  col2  col3
0    1       1  0.308380    23    20
1    1       1  1.185646    35    20
2    1       2 -0.432066    27    20
3    2       2  0.115055    32    27
4    2       3  0.683291    34    20
5    3       4 -1.916321    42    34
6    4       4  0.888327    34    42
7    4       4  1.312879    29    20
8    4       4  1.260612    27    20
9    4       5  0.062635    22    20
10   5       5  0.081149    23    22
11   5       5 -1.872873    32    20

关于python - 根据 pandas 中的情况替换某些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50608418/

相关文章:

python - 用于多输入图像的 VGG16 网络

python - 如何从文件中删除重复行并将其写入Python文件中

python - 如何从带有附加分隔符的 csv 在 python 中创建 pandas 数据框?

python - 重现次数

python - 按最后一个特殊字符将数据帧列拆分为 2 部分

python - python numpy 将对象数组中的元素从 int 转换为 float

python - 如何使用 python 写入 ISO?

python - 如何获取 pandas 中某个项目的第一次和最后一次出现

python - 从 pandas DataFrame 中删除包含空单元格的行

python - 如何加快从 adl ://with fsspec+adlfs? 读取 CSV/Parquet 文件