如何在提取列时保留pandas索引

时间:2017-02-01 03:40:49

标签: python csv pandas

所以我有一个500列600行的文件,想要获取行200-400的所有列的平均值:

df = pd.read_csv('file.csv', sep= '\s+')
sliced_df=df.iloc[200:400]

然后在所有列中创建所有行平均值的新列。并仅提取新创建的列:

sliced_df['mean'] = sliced_df.mean(axis=1)
final_df = sliced_df['mean']

但是,当我提取新列时,如何防止索引重置?

2 个答案:

答案 0 :(得分:1)

我认为没有必要在sliced_df中创建新列,仅rename名称为Series,如果需要输出DataFrame则添加to_frame。索引未重置,请参见下面的示例:

#random dataframe
np.random.seed(100)
df = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (df)
   A  B  C  D  E
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

#in real data use df.iloc[200:400]
sliced_df=df.iloc[2:4]
print (sliced_df)
   A  B  C  D  E
2  2  2  1  0  8
3  4  0  9  6  2

final_ser = sliced_df.mean(axis=1).rename('mean')
print (final_ser)
2    2.6
3    4.2
Name: mean, dtype: float64

final_df = sliced_df.mean(axis=1).rename('mean').to_frame()
print (final_df)
   mean
2   2.6
3   4.2

Python从0计算,因此可能需要从200:400更改切片到100:300,请参阅差异:

sliced_df=df.iloc[1:3]
print (sliced_df)
   A  B  C  D  E
1  0  4  2  5  2
2  2  2  1  0  8

final_ser = sliced_df.mean(axis=1).rename('mean')
print (final_ser)
1    2.6
2    2.6
Name: mean, dtype: float64

final_df = sliced_df.mean(axis=1).rename('mean').to_frame()
print (final_df)
   mean
1   2.6
2   2.6

答案 1 :(得分:0)

使用copy()函数如下:

df = pd.read_csv('file.csv', sep= '\s+')
sliced_df=df.iloc[200:400].copy()
sliced_df['mean'] = sliced_df.mean(axis=1)
final_df = sliced_df['mean'].copy()