如何附加到数据帧中的各个列

2024-04-20 15:54:57 发布

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

因此,我希望向特定的dataFrame列添加/追加数据,但不会在其余列中导致NaN值

DataFrame = pd.DataFrame(columns=["column1", "column2", "column3"])
for i in range():
    DataFrame = DataFrame.append({"column1":int(i)}, ignore_index=True)
    DataFrame = DataFrame.append({"column2":float(i*2)}, ignore_index=True)
    DataFrame = DataFrame.append({"column3":int(i*5)}, ignore_index=True)
print(DataFrame)

这将返回:

   column1  column2  column3
0      0.0      NaN      NaN
1      NaN      0.0      NaN
2      NaN      NaN      0.0
3      1.0      NaN      NaN
4      NaN      2.0      NaN
5      NaN      NaN      5.0
6      2.0      NaN      NaN
7      NaN      4.0      NaN
8      NaN      NaN     10.0

我们想要返回的内容:

   column1  column2  column3
0      0.0      0.0      0.0
1      1.0      2.0      5.0
2      2.0      4.0     10.0

我知道在这种情况下我可以为所有不同的列使用一个.append。但在某些情况下,要附加的数据会根据多种条件而变化。因此,我想知道是否可以在数据帧中附加到单个列,而不在其余列中生成NaN值。这样我就可以避免写成百上千的if-else语句

或者,如果有人对如何“折叠”NaN值有什么好主意(删除NaN值而不删除整行,这样,如果第3列的索引0处有一个NaN值,而同一列的索引1处有一个整数5,则整数5将上移到索引0)

很高兴听到任何想法


Tags: 数据truedataframeindex情况整数nanint
1条回答
网友
1楼 · 发布于 2024-04-20 15:54:57

IIUC对于当前示例,您可以尝试以下方法:

DataFrame[['column2','column3']]=DataFrame[['column2','column3']].bfill()

输出:

 column1  column2   column3
0   0.0     0.0     0.0
1   NaN     0.0     0.0
2   NaN     2.0     0.0
3   1.0     2.0     5.0
4   NaN     2.0     5.0
5   NaN     4.0     5.0
6   2.0     4.0     10.0
7   NaN     4.0     10.0
8   NaN     6.0     10.0
9   3.0     6.0     15.0
10  NaN     6.0     15.0
11  NaN     8.0     15.0
12  4.0     8.0     20.0
13  NaN     8.0     20.0
14  NaN     NaN     20.0

然后删除NaN

DataFrame.dropna(inplace=True)

输出:

 column1  column2   column3
0   0.0     0.0     0.0
3   1.0     2.0     5.0
6   2.0     4.0     10.0
9   3.0     6.0     15.0
12  4.0     8.0     20.0

相关问题 更多 >