如何用变量值填充pandas数据帧中的NaN值?

2024-06-07 12:10:13 发布

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

我有一个数据帧:

   Isolate1 Isolate2 Isolate3 Isolate4
2  NaN      NaN      AGTCTA   AGT
5  NaN      GC       NaN      NaN

并希望用破折号替换Isolate1列中的NaN值,对于其他列中的非NaN值中的每个字母(如果其他列有其他不同的值,则为最大值),以如下形式结束:

^{pr2}$

我试过以下方法:

index_sizes_to_replace = {}
for row in df.itertuples():
    indel_sizes = []
    #0 pos is index
    for i, value in enumerate(row[1:]):
        if pd.notnull(value):
            indel_sizes.append((i, len(value)))
    max_size = max([size for i, size in indel_sizes])
    index_sizes_to_replace[row[0]]= max_size

现在我有了替换NaN值的破折号,但不知道如何填充,尝试了以下方法:

for index, size in index_sizes_to_replace.iteritems():
    df.iloc[index].fillna("-"*size, inplace=True)

但没用,有什么建议吗?在


Tags: to方法inforsizeindexvaluenan
3条回答

它看起来有点难看,但它确实起了作用:

import pandas as pd
import numpy as np

data = dict(Isolate1=[np.NaN,np.NaN],
            Isolate2=[np.NaN,'GC'],
            Isolate3=['AGTCTA',np.NaN],
            Isolate4=['AGT',np.NaN])

df = pd.DataFrame(data)

df['Isolate1'] = (df.drop('Isolate1',1).ffill(axis=1).bfill(axis=1)
                         .iloc[:,0].replace('.', '-', regex=True))

print(df)

退货

^{pr2}$

让我们试试:

import pandas as pd
import numpy as np

data = dict(Isolate1=[np.NaN,np.NaN,'A'],
            Isolate2=[np.NaN,'ABC','A'],
            Isolate3=['AGT',np.NaN,'A'],
            Isolate4=['AGTCTA',np.NaN,'A'])

df = pd.DataFrame(data)

原液:

^{pr2}$

要忽略Isolate1:

df['Isolate1'] = df.iloc[:,1:].apply(lambda x: x.str.len().max().astype(int)*'-', axis=1)

输出:

  Isolate1 Isolate2 Isolate3 Isolate4
0            NaN      AGT   AGTCTA
1       -      ABC      NaN      NaN
2        -        A        A        A

@Anton vBR Edit来处理col1中的not nan。在

# Create a mask
m = pd.isna(df['Isolate1'])
df.loc[m,'Isolate1'] = df[m].apply(lambda x: '-' * x.str.len().max().astype(int), axis=1)

输出:

  Isolate1 Isolate2 Isolate3 Isolate4
0            NaN      AGT   AGTCTA
1       -      ABC      NaN      NaN
2        A        A        A        A

设置

df

  Isolate1 Isolate2 Isolate3 Isolate4
0      NaN      NaN      AGT   AGTCTA
1      NaN      ABC      NaN      NaN
2        A        A        A        A

解决方案
使用fillna+apply+str.__mul__

^{pr2}$

相关问题 更多 >

    热门问题