gpt4 book ai didi

python - 将列的百分比设置为 0( Pandas )

转载 作者:太空宇宙 更新时间:2023-11-04 04:48:07 25 4
gpt4 key购买 nike

我有一个 pandas 数据框,我想将列的某个百分比设置为 0。假设 df 有两列。

  A   B  
1 6
2 7
3 8
4 4
5 9

我现在想将 df 的前 20% 和后 20% 的 B 设置为 0。

  A   B  
1 0
2 7
3 8
4 4
5 0

最佳答案

使用numpy.r_用于连接第一个和最后一个位置,然后按 iloc 更改值, 对于 B 列的位置使用 Index.get_loc :

N = .2
total = len(df.index)
#convert to int for always integer
i = int(total * N)
idx = np.r_[0:i, total-i:total]
df.iloc[idx, df.columns.get_loc('B')] = 0

或者:

N = .2
total = len(df.index)
i = int(total * N)
pos = df.columns.get_loc('B')

df.iloc[:i, pos] = 0
df.iloc[total - i:, pos] = 0

print (df)
A B
0 1 0
1 2 7
2 3 8
3 4 4
4 5 0

编辑:

如果Sparsedataframe并且相同类型的值可以转换为 numpy 数组,设置值并转换回:

arr = df.values
N = .2
total = len(df.index)
i = int(total * N)
pos = df.columns.get_loc('B')
idx = np.r_[0:i, total-i:total]

arr[idx, pos] = 0
print (arr)
[[1 0]
[2 7]
[3 8]
[4 4]
[5 0]]

df = pd.SparseDataFrame(arr, columns=df.columns)
print (df)
A B
0 1 0
1 2 7
2 3 8
3 4 4
4 5 0

print (type(df))
<class 'pandas.core.sparse.frame.SparseDataFrame'>

编辑1:

另一种解决方案是先转换为密集,然后再转换回来:

df = df.to_dense()
#apply solution
df = df.to_sparse()

关于python - 将列的百分比设置为 0( Pandas ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49030144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com