我想将列表作为列添加到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的输出。
答案 0 :(得分:1)
将列表添加为Series
将直接处理此问题。
D = [11,17,18]
df.loc[:, 'D'] = pd.Series(D)
答案 1 :(得分:1)
pd.concat
上的简单df
和一系列D
如下:
pd.concat([df, pd.Series(D, name='D')], axis=1)
或
df.assign(D=pd.Series(D))
Out[654]:
A B C D
0 1 2.0 3.0 11.0
1 5 6.0 9.0 17.0
2 4 NaN NaN 18.0
3 6 NaN 6.0 NaN
4 8 NaN 4.0 NaN
5 2 NaN 3.0 NaN
6 4 NaN NaN NaN
7 6 NaN 6.0 NaN
8 8 NaN 4.0 NaN