我有一个sparse Dataframe ,希望将所有非空值作为一列。请看我制作的说明问题的图片。我设法使用下面的python代码解决了这个问题。但是,我觉得可能有一些更好的|更简单的|有效的解决方法
import pandas as pd
list1 = ["x1","x2","?","?","?","?"]
list2 = ["?","?","y1","y2","?","?"]
list3 = ["?","?","?","?","z1","z2"]
df_sparse = pd.DataFrame({"A":list1,"B":list2,"C":list3})
values_vect = []
for col in df_sparse.columns:
values = [ i for i in list(df_sparse[col]) if i !="?"]
values_vect.extend(values)
df_sparse["D"] = pd.DataFrame(values_vect,columns=["D"])
display(df_sparse)
2条答案
按热度按时间neekobn81#
得到
42fyovps2#
使用掩码
stack
和groupby.last
:输出: