简体   繁体   English

如何在没有 NaN 的情况下使用 pandas 合并不同的列?

[英]How can I merge different columns using pandas without NaN?

I am trying to merge different columns and I used code as follows:我正在尝试合并不同的列,我使用的代码如下:

r1= len(data['Answer_h1_Happy'])
c1 = len(list(data))

ndata1 = list(data.Answer_h1_Happy) + list(data.Answer_h1_Happy) + 
    list(data.Answer_h1_Happy) + list(data.Answer_h1_Happy) \
    + list(data.Answer_h1_Happy) + list(data.Answer_h1_Happy) + 
    list(data.Answer_h1_Happy) + list(data.Answer_h1_Happy) \
    + list(data.Answer_h1_Happy) + list(data.Answer_h1_Happy)
r1 = len(ndata1) - r1
t1 = r1 * c1
dfnan1 = pd.DataFrame(np.reshape([np.nan]*t1, (r1,c1)), columns=list(data))
data= data.append(dfnan1)
data['Happy'] = ndata1

When I try to merge only this, it works well.当我尝试仅合并它时,它运行良好。 But when I try to merge other columns, because of 'NaN' the column get thousands of rows.但是当我尝试合并其他列时,由于“NaN”,该列会获得数千行。

For example, the original table looks like this: original table例如,原始表如下所示: original table

And after 1st merge, NaNs are created in black rows.在第一次合并之后,NaN 在黑色行中创建。 after 1st merge第一次合并后

When I try to merge other column, it gets twice longer than other.当我尝试合并其他列时,它比其他列长两倍。 after 2nd merge第二次合并后

Is there any way I can merge without Nan?没有南我有什么办法可以合并吗? This is what I want这就是我要的

I move combined columns to another data frame.我将组合列移动到另一个数据框。 After that code I add,在我添加的代码之后,

df['Input_image_url'] = data.pop('Input_image_url').reset_index(drop=True)

and remove all NaN by,并通过以下方式删除所有 NaN,

update_data = data.drop(df.index[13:130])

And it works!!它有效!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM