[英]Pandas dataframe groupby remove column
我偶然發現了 dataframe 的問題。 我使用此代碼段生成 dataframe 之后,我根據'chr' Column按 dataframe 分組。
import pandas as pd
DF = pd.DataFrame({'chr':["chr3","chr3","chr7","chr6","chr1", "chr7"],'y':[10,20,30,40,50,90],'ds':
['2018-01-01', '2018-01-02', '2018-01-01', '2018-01-01', '2018-01-01', '2018-12-01']})
DF.head(n=10)
chr y ds
0 chr3 10 2018-01-01
1 chr3 20 2018-01-02
2 chr7 30 2018-01-01
3 chr6 40 2018-01-01
4 chr1 50 2018-01-01
5 chr7 90 2018-12-01
ans = [pd.DataFrame(y) for x, y in DF.groupby('chr', as_index=False)]
ans
[ chr y ds
4 chr1 50 2018-01-01,
chr y ds
0 chr3 10 2018-01-01
1 chr3 20 2018-01-02,
chr y ds
3 chr6 40 2018-01-01,
chr y ds
2 chr7 30 2018-01-01
5 chr7 90 2018-12-01]
請注意,一旦我使用groupby ,我會將結果存儲在列表中。 結果,我列出了基於chr的嵌套dataframe列表。 如果我需要從我的列表中刪除每個子 dataframe 中的 chr 列,該怎么辦? 我只需要從列表中刪除每個 dataframe 中的chr 。 請注意,解決方案應該在更大的列表大小上進行擴展。
如果只有兩列,您可以在創建原始列表時執行此操作:
ans = [pd.DataFrame(y, columns=DF.columns.difference(['chr'])) for x, y in DF.groupby('chr', as_index=False)]
或者,從每個 subDf 顯式刪除chr
:
ans = [pd.DataFrame(y).drop('chr', axis=1) for x, y in DF.groupby('chr', as_index=False)]
如果在創建原始列表時無法刪除(如上所示),您可以像這樣更新它:
# Create `ans` as you're currently doing:
ans = [pd.DataFrame(y) for x, y in DF.groupby('chr', as_index=False)]
#
# some processing on `ans`
#
# Now update `ans` by dropping "chr" from each subDf
ans = [df.drop('chr', axis=1) for df in ans]
這將在保存期間刪除列chr
:
ans = [pd.DataFrame(y).drop('chr', axis=1) for x, y in DF.groupby('chr', as_index=False)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.