繁体   English   中英

Pandas:根据另一列的值从一列中提取值

[英]Pandas: Extract values from a column based on the values from another column

现在我有一个索引label_index列表。 我想根据索引从数据帧label_file提取相应的值。 label_index将出现在列image_num在数据帧和目标是获得相应值的列表Thermal conductivity(W/mK)列。

label_file = pd.read_excel("/Users/yixuansun/Documents/Research/ThermalConductiviy/Anisotropic/anisotropic_porous_media/data.xlsx",
                            sheet_name = "total")
label = []

for i in label_index:
    for j in range(len(label_file)):
        if i == label_file.iloc[j]["image_num"]:
            label.append(label_file.iloc[j]["Thermal conductivity(W/mK)"])

我使用蛮力找到匹配项(两个 for 循环)。 需要很长时间才能通关。 我想知道是否有更有效的方法来做到这一点。

获取列“热导率(W/mK)”,其中“image_num”列具有label_index列表中指定的值之一:

series = label_file.loc[
    label_file['image_num'].isin(label_index),
    'Thermal conductivity(W/mK)']

编辑 1:对于按label_index排序,您可以使用辅助列如下:

df = label_file.loc[
    label_file['image_num'].isin(label_index),
    ['Thermal conductivity(W/mK)', 'image_num']]
# create aux. column to sort by
df['sortbyme'] = df['image_num'].apply(lambda x: label_index.index(x))

# sort by aux. column and get only 'Thermal conductivity(W/mK)' column
series = df.sort_values('sortbyme').reset_index()['Thermal conductivity(W/mK)']

实际上,我自己找到了一种快速但更清洁的方法。

ther = []
for i in label_index:
    ther.append(label_file.loc[i]["Thermal conductivity(W/mK)"])

这将完成工作。

暂无
暂无

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

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