【发布时间】:2019-07-11 03:58:17
【问题描述】:
我想将列表作为列添加到 df 数据框。列表的大小与列的长度不同。
df =
A B C
1 2 3
5 6 9
4
6 6
8 4
2 3
4
6 6
8 4
D = [11,17,18]
我想要以下输出
df =
A B C D
1 2 3 11
5 6 9 17
4 18
6 6
8 4
2 3
4
6 6
8 4
我正在执行以下操作,通过添加“nan”将列表扩展到数据框的大小
# number of nan value require for the list to match the size of the column
extend_length = df.shape[0]-len(D)
# extend the list
D.extend(extend_length * ['nan'])
# add to the dataframe
df["D"] = D
A B C D
1 2 3 11
5 6 9 17
4 18
6 6 nan
8 4 nan
2 3 nan
4 nan
6 6 nan
8 4 nan
其中“nan”被视为字符串,但我希望它为空而不是“nan”,因此,如果我在 D 列中搜索有效单元格的数量,它将提供 3 的输出。
【问题讨论】: