add columns different length pandas

后端 未结 4 1814
闹比i
闹比i 2020-12-02 09:22

I have a problem with adding columns in pandas. I have DataFrame, dimensional is nxk. And in process I wiil need add columns with dimensional mx1, where m = [1,n], but I don

4条回答
  •  没有蜡笔的小新
    2020-12-02 10:01

    I had the same issue, two different dataframes and without a common column. I just needed to put them beside each other in a csv file.

    • Merge: In this case, "merge" does not work; even adding a temporary column to both dfs and then dropping it. Because this method makes both dfs with the same length. Hence, it repeats the rows of the shorter dataframe to match the longer dataframe's length.
    • Concat: The idea of The Red Pea didn't work for me. It just appended the shorter df to the longer one (row-wise) while leaving an empty column (NaNs) above the shorter df's column.
    • Solution: You need to do the following:
    df1 = df1.reset_index()
    df2 = df2.reset_index()
    df = [df1, df2]
    df_final = pd.concat(df, axis=1)
    
    df_final.to_csv(filename, index=False)
    

    This way, you'll see your dfs besides each other (column-wise), each of which with its own length.

提交回复
热议问题