Skip to main content
 首页 » 编程设计

python之如何高效地在 DataFrame 中搜索一个值并将其放入另一个 DataFrame

2024年10月24日10mfrbuaa

我有两个 CSV 文件:

文件1

id  text_feature  value 
1   feature2      20 
1   feature3      5 
2   feature2      20 
... 

文件2

id  feature2  feature3 
1   1         1 
2   1         0 
... 

基于这些文件,我想获得以下文件(即用 values 替换 1 和 0):

文件3

id  feature2  feature3 
1   20        5 
2   20        0 
... 

这就是我尝试解决任务的方式,但它需要很长时间(我的 CSV 文件有大约 20,000 个条目):

import pandas as pd 
 
def find_value(df_data, df_row, column_name): 
    value = 0 
    for index, row in df_data.iterrows(): 
        f = row['feature'].replace(' ','') 
        if row['id'] == df_row['id'] and f == column_name: 
            value = row['volume'] 
            break 
    return value 
 
df_data = pd.read_csv("File1.csv") 
df_textfeatures = pd.read_csv("File2.csv") 
 
for index, row in df_textfeatures.iterrows(): 
    for column_name, column in df_textfeatures.transpose().iterrows(): 
        row[column_name] = find_value(df_data, row, column_name) 

请您参考如下方法:

您可以直接旋转名为 file1 的 dataframe:

d = file1.pivot_table(index='id',columns='text_feature',values='value') 

返回:

text_feature  feature2  feature3 
id                               
1                   20         5 
2                   20       NaN 

为了得到你需要的东西,你可以用 0 填充 NaN 值:

d.fillna(0) 

返回:

text_feature  feature2  feature3 
id                               
1                   20         5 
2                   20         0 

编辑:

然后您必须重置索引以使索引设置为列:

d.reset_index() 

返回:

text_feature  id  feature2  feature3 
0              1        20         5 
1              2        20         0