为什么 np.where 将我的一些数据转换为 NaN 值?

问题描述 投票:0回答:1

我想分割数据值,如果 出现在一个专栏中。这是我的原始数据列的片段(请注意,我将此列转换为

object
数据类型):

0               881567905
1               881046000
2               881046025
3               882935053
4               881006805
5               882130610
6               882036810
7               882428300
8               882428400
9    884343355\n183055900

我在

'\n'
上拆分数据,然后在数据具有使用
np.where()
函数创建的多个列表元素的任何位置返回一个列表。虽然它确实在一定程度上实现了这一点,但它也创建了随机
Nan
值。

0                 881567905
1                 881046000
2                 881046025
3                       NaN
4                       NaN
5                       NaN
6                       NaN
7                 882428300
8                 882428400
9    [884343355, 183055900]

如您所见,未转换的值和替换为 NaN 的值实际上没有任何长度、数据类型或结构差异。我用来拆分和替换的代码是:

file_no = df['file_no'].str.split("\n")
df['file_no'] = np.where(file_no.str.len()==1,file_no.str[0],file_no)

我在结构非常相似的其他列上使用了它,但它没有创建这些

NaN
值。我还重新加载了我的环境,以防我搞砸了一个较小的步骤,但在此之前唯一的代码是:

df = r'Z:\clients.xlsx'
df = pd.read_excel(path,sheet_name="Master List",header=0,engine="openpyxl")
df = df.rename(columns={'Our File #':'file_no', 'ID #':'ID'})
df = df.astype({'file_no':'object'})
df = df[df.file_no.notnull()]

有人知道为什么这些

NaN
值可能会取代那些 pandas 值吗?

python pandas dataframe numpy nan
1个回答
0
投票

我发现使用 .apply 方法效果非常好!如果有更好的方法,我愿意学习另一种解决方案,但这非常有效!

df['file_no'] = df['file_no'].apply(lambda x: x.split('\n') if isinstance(x, str) and '\n' in x else x)
输出:

0                  881567905
1                  881046000
2                  881046025
3                  882935053
4                  881006805
5                  882130610
6                  882036810
7                  882428300
8                  882428400
9     [884343355, 183055900]
10                 884080135
11                 881076100
12                 885052617
13                 885148004
14                 874545945
© www.soinside.com 2019 - 2024. All rights reserved.