基于idx系列设置数据帧值

2024-09-27 21:27:22 发布

您现在位置:Python中文网/ 问答频道 /正文

给定数据帧df

A       B       C
0.10    0.83    0.07
0.40    0.30    0.30
0.70    0.17    0.13    
0.72    0.04    0.24    
0.15    0.07    0.78    

以及系列s

A    3
B    0
C    4
dtype: int64

有没有办法轻松设置
A3元素,
B&;的0元素 列C
4元素没有在序列上循环?你知道吗

徒劳的东西:

df.loc[s] = 'spam'

(但这会设置整行)

所需输出为:

A       B       C
0.10    spam    0.07
0.40    0.30    0.30
0.70    0.17    0.13    
spam    0.04    0.24    
0.15    0.07    spam    

Tags: 数据元素df序列spamlocampdtype
2条回答

有几种方法可以做到这一点。两者都需要将数据转换为object类型,以便将字符串分配给以前的float序列。你知道吗

选项1:numpy

这要求您通过整数数组或元组列表输入坐标。你知道吗

import numpy as np

# convert to numpy object array
vals = df.values.astype(object)

# transform coordinates
coords = [(3, 0), (0, 1), (4, 2)]
idx = np.r_[coords].T

# apply indices
vals[idx[0], idx[1]] = 'spam'

# create new dataframe
res = pd.DataFrame(vals, index=df.index, columns=df.columns)

print(res)

      A     B     C
0   0.1  spam  0.07
1   0.4   0.3   0.3
2   0.7  0.17  0.13
3  spam  0.04  0.24
4  0.15  0.07  spam

方案2:pd.DataFrame.at数据帧你知道吗

一个非矢量化但更直接的解决方案是在for循环中使用^{}

coords = [(3, 'A'), (0, 'B'), (4, 'C')]

df = df.astype(object)

for row, col in coords:
    df.at[row, col] = 'spam'

print(df)

      A     B     C
0   0.1  spam  0.07
1   0.4   0.3   0.3
2   0.7  0.17  0.13
3  spam  0.04  0.24
4  0.15  0.07  spam

我们是上面定义的级数。你知道吗

然后,我们首先在底层数组中将值设置为np.nan,然后分配'spam'。你知道吗

df.values[s.values, np.arange(s.size)] = np.nan # this modifies the dataframe in-place
df.fillna('spam', inplace=True)

输出:

      A     B     C
0   0.1  spam  0.07
1   0.4   0.3   0.3
2   0.7  0.17  0.13
3  spam  0.04  0.24
4  0.15  0.07  spam

相关问题 更多 >

    热门问题