如何使用pandas从数据框中选择行和列

时间:2015-06-10 11:27:35

标签: python pandas dataframe

我目前有以下代码:

import glob
import pandas as pd

path_pattern = 'C:/Users/Joey/Desktop/GC results/Results/FID_00*'
files = glob.glob(path_pattern)
dataframes = [pd.DataFrame.from_csv(f, index_col=None) for f in files]

new_df = pd.DataFrame()

for i in dataframes:
    selected_data = i['Unnamed: 3'].ix[12:16]  
    new_df['Run'] = selected_data
    print new_df

out:

       Run
12  5187666.22
13  1453339.93
14   193334.09
15   157630.92
16    98943.96
           Run
12  5188329.28
13  1455640.31
14      193074
15   157420.83
16    98791.72
           Run
12  5188943.17
13  1456575.95
14   192977.15
15   157325.56
16    98699.43
           Run
12   5188675.1
13  1456622.43
14   192796.99
15   157174.61
16    98598.53
           Run
12  5187783.26
13  1456612.29
14   192703.05
15   157078.52
16    98511.48

目前,选择都在同一列中。是否有可能重新组织这样,每个选择12-16是一个单独的列?我想run1,run2,...,run6是6个独立的列。

1 个答案:

答案 0 :(得分:1)

使用.ix选择所需数据,并将所选数据(类型:pd.Series)添加到新数据框:

# create new dataframe for selected data
new_df = pd.DataFrame()

# placeholder for six selections (i = 1...6)
for i, df in enumerate(dataframes):
    colname = 'Run {}'.format(i+1)
    selected_data = i['Unnamed: 3'].ix[12:16]  
    new_df[colname] = selected_data
    print new_df