[英]Finding the mean of consecutive columns
我有一個非常大的數據文件(數萬行和列),其格式與此類似。
name x y gh_00hr_bio_rep1 gh_00hr_bio_rep2 gh_00hr_bio_rep3 gh_06hr_bio_rep1
gene1 x y 2 3 2 1
gene2 x y 5 7 6 2
我對每個基因的目標是找到每組重復的平均值。
最后,我只想擁有標題為“00hr_bio”之類的平均值列,並刪除所有單獨的重復。
我現在的想法是使用這樣的東西:
for row in df:
df[avg] = df.iloc[3:].rolling(window=3, axis=1).mean()
但我不知道如何真正做到這一點。
df.iloc[3]
是我嘗試從第 3 列開始的方式,但我相當肯定這樣做是行不通的。
我什至不知道從哪里開始將 3 列“合並”為 1。
您的任何建議將不勝感激,因為我顯然不知道自己在做什么。
我將首先構建一系列由原始列索引的最終名稱:
names = pd.Series(['_'.join(i.split('_')[:-1]) for i in df.columns[3:]],
index = df.columns[3:])
然后我會用它來詢問軸 1 上的 groupby 的平均值:
tmp = df.iloc[:, 3:].groupby(names, axis=1).agg('mean')
它提供了一個新的 dataframe 索引,與原始索引一樣並具有平均列:
gh_00hr_bio gh_06hr_bio
0 2.333333 1.0
1 6.000000 2.0
然后,您可以將其水平連接到第一個 dataframe 或其前 3 列:
result = pd.concat([df.iloc[:, :3], tmp], axis=1)
要得到:
name x y gh_00hr_bio gh_06hr_bio
0 gene1 x y 2.333333 1.0
1 gene2 x y 6.000000 2.0
你很接近。
df['avg'] = df.iloc[:, 2:].mean(axis=1)
會給你這個:
x y gh_00hr_bio_rep1 gh_00hr_bio_rep2 gh_00hr_bio_rep3 gh_06hr_bio_rep1 avg
gene1 x y 2 3 2 1 2.0
gene2 x y 5 7 6 2 5.0
如果您希望從不同的列集中獲得平均值,您可以執行以下操作:
for col in range(10):
df['avg%i' % col] = df.iloc[:, 2+col*5:7+col*5].mean(axis=1)
如果您的平均列數相同。 否則,您可能希望使用代表列的名稱,具體取決於您的數據的樣子。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.