熊猫数据框循环

时间:2018-10-15 13:12:00

标签: python pandas dataframe

我坚持下面的代码。基本上,我使用循环变量“ analyticalname”和“ fedbatchname”遍历2个数据帧的第一列。如果这两个变量在每个数据框中都找到一个匹配项,那么我想根据循环变量的值来访问数据框中的那个元素。但是,当我运行代码时,出现了一个关键错误,该错误源于if语句之后的那一行。本质上,我是在问如何基于循环变量访问数据帧的元素。有什么建议吗?

import pandas as pd
analyticaldata = pd.read_csv('SE-HPLC.csv', usecols = ['Sample ID','% 
Aggregate','% Monomer','% Fragment']) #loading data into pandas DataFrame
fedbatchdata = pd.read_csv('Culture Day Sheet.csv',usecols = 
['RUN_NUMBER','% Aggregate','% Monomer','% Fragment'])

for analyticalname in analyticaldata['Sample ID']: #for each element in 
first column of SE-HPLC worksheet
for fedbatchname in fedbatchdata['RUN_NUMBER']: #for each element in first column of Culture Day worksheet
    if analyticalname == fedbatchname: #if any of the names match
        fedbatchdata.ix[fedbatchdata.fedbatchname,'% Aggregate'] = analyticaldata[analyticalname]['% Aggregate']
        fedbatchdata.ix[fedbatchdata.fedbatchname,'% Monomer'] = analyticaldata.ix[analyticalname,'% Monomer']                  
        fedbatchdata.ix[fedbatchdata.fedbatchname,'% Fragment'] = analyticaldata.ix[analyticalname,'% Fragment']

编辑:这是这两个数据框的一些示例数据,对于为您省去这些数据,我深表歉意。 fedbatch数据框应该为空,我正在尝试将分析数据框中的值复制到fedbatch数据框中。

Analytical dataframe:
SAMPLE_ID:    % Aggregate    % Monomer    % Fragment
A               2             4             1.5
B               1             4             6
C               5             5             2.1
D               3             7.1           10

Fed Batch Dataframe:
RUN_NUMBER:    % Aggregate    % Monomer    % Fragment
B                                        
A                                                                                   
C
D                                                  

1 个答案:

答案 0 :(得分:1)

在重命名列中使用merge,以避免在输出DataFrame中使用它,而仅从RUN_NUMBER中选择列fedbatchdata

df = (fedbatchdata[['RUN_NUMBER']]
                    .merge(analyticaldata.rename(columns={'Sample ID':'RUN_NUMBER'}), 
                          on=['RUN_NUMBER'], 
                          how='left'))
print (df)
  RUN_NUMBER  % Aggregate  % Monomer  % Fragment
0          B            1        4.0         6.0
1          A            2        4.0         1.5
2          C            5        5.0         2.1
3          D            3        7.1        10.0