2 回答

TA貢獻1794條經驗 獲得超8個贊
我想我知道你在做什么課程,一年前我玩得很開心,堅持下去!
我發現連接一堆切片數據幀的最簡單/最快的方法是將每個 df 附加到一個列表,然后最后連接該列表。請參閱下面的工作代碼(它按照我的意思解釋您的意思)。
我同意 David 關于排序的建議,更易于使用排序,然后只對前 3 個進行切片。 由于 nlargest() 工作并返回一個我相信的系列而不是數據框,而您想要保留整個數據框結構(所有列) 進行串聯。
另外為什么你的函數返回1?錯別字?我想如果你把它放在一個函數中,你想返回你想要的輸出,所以我也改變了它。
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貢獻1805條經驗 獲得超9個贊
歡迎來到 SO!您的問題是追加還是前三行?
對于追加,請嘗試df.append函數。它可能看起來像:
#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
對于頂行,您可以使用 df.sort_values(by=['column name'],ascending=False) 然后選擇前三行:
population_df = population_df.append(temp_df[0:3], ignore_index = True)
添加回答
舉報