我有大量列的資料:
df:
ID col1 col2 col3 ... col100
1 a x 0 1
1 a x 1 1
2 a y 1 1
4 a z 1 0
...
98 a z 1 1
100 a x 1 0
我想ID用默認值填充缺失值,表明此處缺少資料。例如在這里ID 3,假設說丟失的行資料看起來像ID 100
ID col1 col2 col3 ... col100
3 a x 1 0
99 a x 1 0
預期輸出:
df:
ID col1 col2 col3 ... col100
1 a x 0 1
1 a x 1 1
2 a y 1 1
3 a x 1 0
4 a z 1 0
...
98 a z 1 1
99 a x 1 0
100 a x 1 0
我也同意 3 和 99 在底部。
我嘗試了幾種附加新行的方法:
noresponse = df[filterfornoresponse].head(1).copy() #assume that this will net us row 100
for i in range (1, maxID):
if len(df[df['ID'] == i) == 0: #IDs with no rows ie missing data
temp = noresponse.copy()
temp['ID'] = i
df.append(temp, ignore_index = True)
此方法似乎沒有附加任何內容。
我也試過
pd.concat([df, temp], ignore_index = True)
代替 df.append
我還嘗試將行添加到串列中noresponserows,目的是將串列與df:
noresponserows = []
for i in range (1, maxID):
if len(df[df['ID'] == i) == 0: #IDs with no rows ie missing data
temp = noresponse.copy()
temp['ID'] = i
noresponserows.append(temp)
但在這里,當我知道在我的資料中有不止一行需要附加時,串列總是只有 1 行。
I'm not sure why I am having trouble appending more than once instance of noresponse into the list, and why I can't directly append to a dataframe. I feel like I am missing something here.
I think it might have to do with me taking a copy of a row in the df vs constructing a new one. The reason why I take a copy of a row to get noresponse is because there are a large amount of columns so it is easier to just take an existing row.
uj5u.com熱心網友回復:
假設你有一個這樣的資料框:
>>> df
col1 col2 col100 ID
0 a x 0 1
1 a y 3 2
2 a z 1 4
首先,將ID列設定為索引:
>>> df = df.set_index('ID')
>>> df
col1 col2 col100
ID
1 a x 0
2 a y 3
4 a z 1
現在您可以使用df.loc輕松添加行。
讓我們選擇最后一行作為默認行:
>>> default_row = df.iloc[-1]
>>> default_row
col1 a
col2 z
col100 1
Name: 4, dtype: object
我們可以將它直接添加到 ID 3 處的資料幀中:
>>> df.loc[3] = default_row
>>> df
col1 col2 col100
ID
1 a x 0
2 a y 3
4 a z 1
3 a z 1
然后使用sort_index按索引按字典順序對行進行排序:
>>> df = df.sort_index()
>>> df
col1 col2 col100
ID
1 a x 0
2 a y 3
3 a z 1
4 a z 1
并且,可選地,重置索引:
>>> df = df.reset_index()
>>> df
ID col1 col2 col100
0 1 a x 0
1 2 a y 3
2 3 a z 1
3 4 a z 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/386215.html
