简体   繁体   English

更新变量中的熊猫数据框行

[英]Updating pandas dataframe row in a variable

I'm doing the following to update a dataframe row: 我正在执行以下操作来更新数据框行:

val = "123"
row = df.loc[id, :]
t = type(row['col1'])
val = t(val)
df.loc[id, 'col1'] = val

If I do row['col1'] = val, it doesn't update the original dataframe. 如果我执行row ['col1'] = val,则不会更新原始数据帧。 Is there a way to update the original dataframe without using .loc twice? 有没有一种方法可以在不使用.loc两次的情况下更新原始数据帧?

Updated for comment below 更新以下评论
I believe the short answer is no to 我相信简短的答案是

Is there someway of saying "change the row you've already fetched" 是否有某种方式说“更改您已经获取的行”

This is because operations in Pandas return a copy not a view to the original DataFrame. 这是因为Pandas中的操作会返回一个副本,而不是原始DataFrame的视图。 There is a StackOverflow post from JeffR who writes much of Pandas here JeffR有一个StackOverflow帖子, 在这里写了很多《熊猫》

If you're trying to assign the val to one cell in the DataFrame you can use the set_value function. 如果您尝试将val分配给DataFrame中的一个单元格,则可以使用set_value函数。 The documentation for that method is here . 该方法的文档在这里

val = "123"
row = df.loc[id, :]
t = type(row['col1'])
val = t(val)
df.set_value(id, 'col1', val)

If you're trying to assign the val with particular data type to all cells in column, can use the apply method 如果您尝试将具有特定数据类型的val分配给列中的所有单元格,则可以使用apply方法

def changeType(cell, val):
    # You could pass the id or list of ids as well if you need to perform some logic with it
    t = type(cell)
    cell = t(val)
    return cell

val = "123"
df.loc[:, 'col1'] = df.loc[:, 'col1'].apply(changeType, args=(val,))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM