簡體   English   中英

使用 pandas 將列從較小的數據幀復制(組裝)到較大的數據幀中

[英]Copying (assembling) the column from smaller data frames into the bigger data frame with pandas

我有一個數據框,其中包含幾組參與者的測量結果,並且我正在為每組進行一些計算。 我想從輔助數據框(參與者的部分列表)中在大數據框(所有參與者)中添加一列。

當我合並幾次(將新數據框合並到現有數據框)時,它會創建列的副本而不是一列。

由於數據框的大小不同,我無法直接比較它們。

我試過了

    #df1 - main bigger dataframe,  df2 - smaller dataset contains group of df1
    
    
    for i in range(len(df1)):
    # checking indeces to place the data to correct participant:
        if df1.index[i] not in df2['index']: 
            pass
        else :
            df1['rate'][i] = list(df2[rate][df2['index']==i]) 
    

但它不能正常工作。 你能幫忙看看組裝柱子的正確方法嗎? 更新:初始dataframe的索引與計算的“索引”列相同,將計算中的速率值復制到主df

主 dataframe 1df

指數 速度
1 0
2 0
3 0
4 0
5 0
6 0

dataframe 與計算值

指數 速度
1 價值
4 價值
6 價值

output df

指數 速度
1 價值
2 0
3 0
4 價值
5 0
6 價值

試試這個——使用.join()合並索引上的數據幀,並使用.combine_first()合並兩列:

df = df1.join(df2, lsuffix="_df1", rsuffix="_df2")
df["rate"] = df["rate_df2"].combine_first(df["rate_df1"])

編輯:

這假設兩個數據幀都使用匹配的索引。 如果df2不是這種情況,請先運行:

df2 = df2.set_index('index')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM