2 回答

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超7個(gè)贊
我想我知道你在做什么課程,一年前我玩得很開(kāi)心,堅(jiān)持下去!
我發(fā)現(xiàn)連接一堆切片數(shù)據(jù)幀的最簡(jiǎn)單/最快的方法是將每個(gè) df 附加到一個(gè)列表,然后最后連接該列表。請(qǐng)參閱下面的工作代碼(它按照我的意思解釋您的意思)。
我同意 David 關(guān)于排序的建議,更易于使用排序,然后只對(duì)前 3 個(gè)進(jìn)行切片。 由于 nlargest() 工作并返回一個(gè)我相信的系列而不是數(shù)據(jù)框,而您想要保留整個(gè)數(shù)據(jù)框結(jié)構(gòu)(所有列) 進(jìn)行串聯(lián)。
另外為什么你的函數(shù)返回1?錯(cuò)別字?我想如果你把它放在一個(gè)函數(shù)中,你想返回你想要的輸出,所以我也改變了它。
import pandas as pd
import numpy as np
#create fake data random numbers
data = np.random.randint(2,11,(40,3))
census_df = pd.DataFrame(index=range(40), columns=['Blah', 'Blah2','CENSUS2010POP'], data=data)
#create fake STNAME column
census_df['STNAME'] = list('aaaabbbbccccddddeeeeffffgggghhhhiiiijjjj')
#Function:
def test(census_df):
states_list = census_df.STNAME.unique() #changed naming to _list as it's not a df.
list_of_dfs = list() #more efficient to append each df to a list
for st in states_list:
temp_df = census_df[census_df['STNAME']==st]
temp_df = temp_df.sort_values(by=['CENSUS2010POP'], ascending=False).iloc[:3]
list_of_dfs.append(temp_df)
population_df = pd.concat(list_of_dfs,ignore_index=True)
return population_df
population_df = test(census_df)

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
歡迎來(lái)到 SO!您的問(wèn)題是追加還是前三行?
對(duì)于追加,請(qǐng)嘗試df.append函數(shù)。它可能看起來(lái)像:
#get the list of states
states_df = census_df.STNAME.unique()
population_df = pd.DataFrame()
for st in states_df:
temp_df = pd.DataFrame(census_df[census_df['STNAME'] == st].nlargest(3,'CENSUS2010POP'))
population_df = population_df.append(temp_df, ignore_index = True) #append the temp df to your main df, ignoring the index
對(duì)于頂行,您可以使用 df.sort_values(by=['column name'],ascending=False) 然后選擇前三行:
population_df = population_df.append(temp_df[0:3], ignore_index = True)
添加回答
舉報(bào)