如何使用字符串和列表返回数据框特定的列

时间:2018-07-27 14:26:15

标签: python pandas dataframe

所以,我有一个数据框testDF,其中包含列C1:C6和一个列表:

List = ['C1', 'C2', 'C3', 'C4']

,我想选择这些列以及更多列。

所以,我尝试了:

test1 = testDF.loc[(testDF.C1 == blah) & (testDF.C2== blah)]['C5', 'C6', List]]

返回:

TypeError: unhashable type: 'list'

我知道有可能:

test1 = testDF.loc[(testDF.C1 == blah) & (testDF.C2== blah)][List]

但是,我想考虑将列表和字符串组合以指定列的可能性。

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

这是一个例子:

import pandas as pd

testDF = pd.DataFrame([['something', 'very likely', 3, 4, 5, 6],['something else', 'likely', 9, 10, 11, 12],['not here', 'possible', 15, 16]], columns=['C1','C2','C3','C4','C5','C6'])

收益:

               C1           C2  C3  C4  C5  C6
0       something  very likely   3   4   5   6
1  something else       likely   9  10  11  12
2        not here     possible  15  16  17  18

然后:

List = ['C1', 'C2', 'C3', 'C4']

test1 = testDF.loc[(testDF.C1.str.contains('something')) & (testDF.C2.str.contains('likely'))][List]

收益:

               C1           C2  C3  C4
0       something  very likely   3   4
1  something else       likely   9  10

如果您希望匹配的列(不仅包含列),则可以使用带有正则表达式的str.match,如下所示:

test1 = testDF.loc[(testDF.C1.str.match(r'^something$')) & (testDF.C2.str.match(r'.*?likely'))][List]

收益:

          C1           C2  C3  C4
0  something  very likely   3   4

答案 1 :(得分:0)

我找到了解决方法:

if($_FILES['file_name']['size'] != 0){
    $config['upload_path']          = FCPATH.MEDIA_LIB_URI.'facts';
    $config['allowed_types']        = 'jpg|jpeg|png|gif';
    $config['max_size']             = 0;

    $newFileName = removeExt($_FILES['file_name']['name']).'-'.uniqueId();      // renaming the file name without the ext
    $new_name = $newFileName.getExt($_FILES['file_name']['name']);              // new file name with the ext
    $config['file_name'] = $new_name;

    $this->load->library('upload',$config);
    $this->upload->initialize($config);

    if($this->upload->do_upload('file_name')){
        $uploadData = $this->upload->data();
        $file_name = $uploadData['file_name'];

        $this->load->library('image_lib');
        $configer = array(
            'image_library'   => 'gd2',
            'source_image'    => $uploadData['full_path'],
            'create_thumb'    => TRUE,
            'maintain_ratio'  => TRUE,
            'width'           => 950,
            'height'          => 950,
        );

        $this->image_lib->clear();
        $this->image_lib->initialize($configer);
        $this->image_lib->resize();

        $thumbName = $newFileName.'_thumb'.getExt($_FILES['file_name']['name']);    // getting the exact thumbnail name that been created by codeigniter
        move_uploaded_file($thumbName, FCPATH.MEDIA_LIB_URI.'facts/thumbnail/'.$new_name);

        return $file_name;
    } else {
        return $this->upload->display_errors();
    }
}