Python 根据条件插入索引新行
如图所示,我有一个带有命名索引和两列的索引 如果满足if-else条件,我想添加一个新行。 我尝试了Python 根据条件插入索引新行,python,pandas,dataframe,Python,Pandas,Dataframe,如图所示,我有一个带有命名索引和两列的索引 如果满足if-else条件,我想添加一个新行。 我尝试了df.loc[-1]=[words[0],words[1],1],但我认为它可能适用于未命名的索引 预期产量- system_call frequency file_frequency madvise 300 3 write 277 2 read 23 5 ioctl 45 4
df.loc[-1]=[words[0],words[1],1]
,但我认为它可能适用于未命名的索引
预期产量-
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
可以看出,现在添加了最后一行如果
futex
在索引中不存在,我认为需要:
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
如果存在,将重写行:
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
如果需要,请始终添加新行,并由系列
使用索引作为列名称,并使用名称
作为新索引值:
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
如果要在dataframe中添加具有指定索引值的行
df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
print(df)
具有列名和值的字典。
试试这个Trydf.iloc[-1]=[words[0],words[1],1]
loc
是基于标签的iloc
是整数position@EdChum但是我的数据框有两列,其中包括单词[1]和单词[1],索引是单词[0],如果这是索引“futex”的第一次输入,这会起作用吗?是,如果第一次futex
iot添加新行,如果存在,将重写该行。非常感谢!。。。您知道如何更新pandas中的行吗?我做了df.loc['madvise',130]+=int(单词[1]),但得到了error@ubuntu_noob-什么样的错误<代码>测向定位点['madvise',130]=测向定位点['madvise',130]+10
工作?或者df.loc['madvise',130]+=10
df.loc['madvise',130]=df.loc['madvise',130]+10和df.loc['madvise',130]+=10都给出了错误..这是类型错误:无法使用
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
df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
print(df)
df.loc["21"] = {"A":3,"B":3}
print(df)