我有一个包含两行的数据框
df = pd.DataFrame({'group' : ['c'] * 2,
'num_column': range(2),
'num_col_2': range(2),
'seq_col': [[1,2,3,4,5]] * 2,
'seq_col_2': [[1,2,3,4,5]] * 2,
'grp_count': [2]*2})
有8个空值,它看起来像这样:
df = df.append(pd.DataFrame({'group': group}, index=[0] * size))
group grp_count num_col_2 num_column seq_col seq_col_2
0 c 2.0 0.0 0.0 [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
1 c 2.0 1.0 1.0 [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
0 c NaN NaN NaN NaN NaN
0 c NaN NaN NaN NaN NaN
0 c NaN NaN NaN NaN NaN
0 c NaN NaN NaN NaN NaN
0 c NaN NaN NaN NaN NaN
0 c NaN NaN NaN NaN NaN
0 c NaN NaN NaN NaN NaN
0 c NaN NaN NaN NaN NaN
我想要的:
将序列列(seq_col、seq_col_2、seq_col_3等)中的 NaN值替换为我自己提供的列表。
注意:。
- 在这个数据中,只有2个序列列,但可能会有更多。
- 不能替换已经存在于列中的先前列表, 只能替换NaN
我找不到用字典中提供的用户提供的 列表值替换NaN的解决方案。
伪代码:
for each key, value in dict,
for each column in df
if column matches key in dict
# here matches means the 'seq_col_n' key of dict matched the df
# column named 'seq_col_n'
replace NaN with value in seq_col_n (which is a list of numbers)
我尝试了下面的代码,它可以处理你传递的第一列,但是对于第二列却无法正常工作。这很奇怪。
df.loc[df['seq_col'].isnull(),['seq_col']] = df.loc[df['seq_col'].isnull(),'seq_col'].apply(lambda m: fill_values['seq_col'])
上述方法确实可以解决问题,但是如果在seq_col_2上再次尝试,则会得到奇怪的结果。 期望输出: 给定参数输入:
my_dict = {seq_col: [1,2,3], seq_col_2: [6,7,8]}
# after executing the code from pseudo code given, it should look like
group grp_count num_col_2 num_column seq_col seq_col_2
0 c 2.0 0.0 0.0 [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
1 c 2.0 1.0 1.0 [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
0 c NaN NaN NaN [1,2,3] [6,7,8]
0 c NaN NaN NaN [1,2,3] [6,7,8]
0 c NaN NaN NaN [1,2,3] [6,7,8]
0 c NaN NaN NaN [1,2,3] [6,7,8]
0 c NaN NaN NaN [1,2,3] [6,7,8]
0 c NaN NaN NaN [1,2,3] [6,7,8]
0 c NaN NaN NaN [1,2,3] [6,7,8]
0 c NaN NaN NaN [1,2,3] [6,7,8]