gpt4 book ai didi

python - 每隔一行用特殊条件用 0 替换空值

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

这是数据集的以下子集:

A  B    C         D         R        sentence              ADR1         ADR2     
112 135 21 EffexorXR.21 1 lack of good feeling. good feeling
113 135 21 EffexorXR.21 1 1
115 136 21 EffexorXR.21 2 Feel disconnected disconnected feel
116 136 21 EffexorXR.21 2 0
118 142 22 EffexorXR.22 1 Weight gain gain
119 142 22 EffexorXR.22 1 1

在 ADR1 和 ADR2 列中,对于每个单词,行中应该有 1 或 0。如果缺少该值,我需要将其替换为“0”。这是输出:

A  B    C         D         R        sentence              ADR1         ADR2     
112 135 21 EffexorXR.21 1 lack of good feeling. good feeling
113 135 21 EffexorXR.21 1 1 0
115 136 21 EffexorXR.21 2 Feel disconnected disconnected feel
116 136 21 EffexorXR.21 2 0 0
118 142 22 EffexorXR.22 1 Weight gain gain
119 142 22 EffexorXR.22 1 1

我试过了

df[ADR1].fillna(0, inplace=True) and df[ADR2].fillna(0, inplace=True)

但是这段代码产生了下面的 df,这是不需要的

 A  B    C         D         R        sentence              ADR1         ADR2     
112 135 21 EffexorXR.21 1 lack of good feeling. good feeling
113 135 21 EffexorXR.21 1 1 0
115 136 21 EffexorXR.21 2 Feel disconnected disconnected feel 0
116 136 21 EffexorXR.21 2 0
118 142 22 EffexorXR.22 1 Weight gain gain 0
119 142 22 EffexorXR.22 1 1 0

最佳答案

您可以使用 reshape允许一次处理每隔一行的数据。像这样的东西:

代码:

for col in ['ADR1', 'ADR2']:
data = np.reshape(df[col].values, (-1, 2))
need_fill = np.logical_and(data[:, 0] != '', data[:, 1] == '')
data[np.where(need_fill),1] = 0

测试代码:

import pandas as pd
from io import StringIO
import numpy as np

df = pd.read_fwf(StringIO(u"""
A B C D R sentence ADR1 ADR2
112 135 21 EffexorXR.21 1 lack of good feeling good feeling
113 135 21 EffexorXR.21 1 1
115 136 21 EffexorXR.21 2 Feel disconnected disconnected feel
116 136 21 EffexorXR.21 2 0
118 142 22 EffexorXR.22 1 Weight gain gain
119 142 22 EffexorXR.22 1 1"""),
header=1).fillna('')

print(df)
for col in ['ADR1', 'ADR2']:
data = np.reshape(df[col].values, (-1, 2))
need_fill = np.logical_and(data[:, 0] != '', data[:, 1] == '')
data[np.where(need_fill),1] = 0
print(df)

结果:

     A    B   C             D  R              sentence          ADR1     ADR2
0 112 135 21 EffexorXR.21 1 lack of good feeling good feeling
1 113 135 21 EffexorXR.21 1 1
2 115 136 21 EffexorXR.21 2 Feel disconnected disconnected feel
3 116 136 21 EffexorXR.21 2 0
4 118 142 22 EffexorXR.22 1 Weight gain gain
5 119 142 22 EffexorXR.22 1 1

A B C D R sentence ADR1 ADR2
0 112 135 21 EffexorXR.21 1 lack of good feeling good feeling
1 113 135 21 EffexorXR.21 1 1 0
2 115 136 21 EffexorXR.21 2 Feel disconnected disconnected feel
3 116 136 21 EffexorXR.21 2 0 0
4 118 142 22 EffexorXR.22 1 Weight gain gain
5 119 142 22 EffexorXR.22 1 1

关于python - 每隔一行用特殊条件用 0 替换空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44742392/

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