Raf*_*ios 3 python dataframe pandas
我有一个数据帧:
Isolate1 Isolate2 Isolate3 Isolate4
2 NaN NaN AGTCTA AGT
5 NaN GC NaN NaN
Run Code Online (Sandbox Code Playgroud)
并且想要用破折号替换Isolate1列中的NaN值,对于来自其他列的非NaN值中的每个字母使用一个破折号(如果其他列具有其他不同的值,则为最大数字),以这样的结尾:
Isolate1 Isolate2 Isolate3 Isolate4
2 ------ NaN AGTCTA AGT
5 -- GC NaN NaN
Run Code Online (Sandbox Code Playgroud)
我尝试过以下方法:
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
Run Code Online (Sandbox Code Playgroud)
现在我有多少破折号来替换NaN值,但不知道如何填充,试过这个:
for index, size in index_sizes_to_replace.iteritems():
df.iloc[index].fillna("-"*size, inplace=True)
Run Code Online (Sandbox Code Playgroud)
但没有工作,任何建议?
它看起来有点难看,但它的确如此:
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)
Run Code Online (Sandbox Code Playgroud)
返回
Isolate1 Isolate2 Isolate3 Isolate4
2 ------ NaN AGTCTA AGT
5 -- GC NaN NaN
Run Code Online (Sandbox Code Playgroud)
我们试试吧:
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)
Run Code Online (Sandbox Code Playgroud)
原始解决方案
df['Isolate1'] = df.apply(lambda x: '-' * x.str.len().max().astype(int), axis=1)
Run Code Online (Sandbox Code Playgroud)
要忽略Isolate1:
df['Isolate1'] = df.iloc[:,1:].apply(lambda x: x.str.len().max().astype(int)*'-', axis=1)
Run Code Online (Sandbox Code Playgroud)
输出:
Isolate1 Isolate2 Isolate3 Isolate4
0 ------ NaN AGT AGTCTA
1 --- ABC NaN NaN
2 - A A A
Run Code Online (Sandbox Code Playgroud)
@Anton vBR编辑处理col1中不是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)
Run Code Online (Sandbox Code Playgroud)
输出:
Isolate1 Isolate2 Isolate3 Isolate4
0 ------ NaN AGT AGTCTA
1 --- ABC NaN NaN
2 A A A A
Run Code Online (Sandbox Code Playgroud)