ubuntu_noob
ubuntu_noob

Reputation: 2365

insert an indexed new row based on condition

I have a pandas df with named index and two columns as shown in the picture.

enter image description here

df = pd.DataFrame(columns=['system_call','frequency','file_frequency'])
df.set_index('system_call', inplace=True)

I want to add a new row if a if-else condition is met. I tried df.loc[-1]=[words[0],words[1],1] but I think it might be for non-named indexes.

expected output-

system_call   frequency file_frequency

madvise          300    3
write            277    2
read             23     5
ioctl            45     4
getuid           78     2
epoll_pwait      12     1
futex            13     6

as can be seen the last row is added now

Upvotes: 1

Views: 221

Answers (2)

Narendra Prasath
Narendra Prasath

Reputation: 1531

If you want to add a row in dataframe with specified Index value

df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
print(df)

enter image description here

df.loc["21"] = {"A":3,"B":3}
print(df)

enter image description here

dictionary with column name and value. Try this out

Upvotes: 1

jezrael
jezrael

Reputation: 862641

I believe need if futex not exist in index:

df.loc['futex']=[13,6]

print (df)
             frequency  file_frequency
system_call                           
madvise            300               3
write              277               2
read                23               5
ioctl               45               4
getuid              78               2
epoll_pwait         12               1
futex               13               6

If exist, row is rewritten:

df.loc['madvise']=[130,100]
print (df)
             frequency  file_frequency
system_call                           
madvise            130             100
write              277               2
read                23               5
ioctl               45               4
getuid              78               2
epoll_pwait         12               1

If need always add new row use append by Series with index as columns names and name for new index value:

df = df.append(pd.Series([13,6], name='futex', index=df.columns))
print (df)
             frequency  file_frequency
system_call                           
madvise            300               3
write              277               2
read                23               5
ioctl               45               4
getuid              78               2
epoll_pwait         12               1
futex               13               6

df = df.append(pd.Series([130,100], name='madvise', index=df.columns))
print (df)
             frequency  file_frequency
system_call                           
madvise            300               3
write              277               2
read                23               5
ioctl               45               4
getuid              78               2
epoll_pwait         12               1
madvise            130             100

Upvotes: 1

Related Questions