[英]Pandas, how to merge columns into 1 where all the values are added together
df ['year'] = df.sum(axis = 1)
對於第二個問題,您說明情況是什么,但沒有說明期望的結果是什么。
編輯:我假設“ y”是常數。 對於第二行,如果只需要一行,則可以執行df.loc [1] .sum()。 如果要在數據框中使用,則可以執行new_df = pd.DataFrame([['y'],[df.loc [1] .sum()]])。 如果要多於一行,則可以對range(1,df.shape [0]中的行執行new_df = pd.DataFrame([['y'] + [[df.loc [row] .sum()] ]])
如果要對一行中的所有元素求和,則可以簡單地說df.iloc[row_num].sum()
假設您正在從csv之類的結構化文件格式中讀取內容,則可以執行以下操作。 我也嘗試回答您最初問題的第二部分。
skip-rows
是一個集合,因此它顯然可以容納多個標記為要跳過的行。
##ignore the repeating column-header rows by telling pandas which to skip when reading the file
df = pandas.read_csv('C:\\test.csv', skiprows=[16])
##create a new dataframe where you aggregate the columns into one value, Y
df = pandas.DataFrame(data=df.sum(axis=1), columns=["Y"])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.