Python Pandas - 使用基于索引、列的字典更新行

问题描述 投票:0回答:2

我有一个包含空列的数据框和相应的字典,我想根据索引、列更新空列:

import pandas as pd    
import numpy as np

dataframe = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9], [4, 6, 2], [3, 4, 1]])
dataframe.columns = ['x', 'y', 'z']
additional_cols = ['a', 'b', 'c']

for col in additional_cols:
     dataframe[col] = np.nan

    x   y   z   a  b  c
0   1   2   3           
1   4   5   6           
2   7   8   9           
3   4   6   2           
4   3   4   1           

for row, column in x.iterrows():
    #caluclations to return dictionary y
    y = {"a": 5, "b": 6, "c": 7}
    df.loc[row, :].map(y)

基本上在使用 x、y、z 列执行计算后,我想更新同一行的 a、b、c 列:)

python-3.x pandas dictionary
2个回答
5
投票

我可以使用这样的函数,但就 pandas 库和 DataFrame 对象的方法而言,我不确定:

def update_row_with_dict(dictionary, dataframe, index):  
    for key in dictionary.keys():  
        dataframe.loc[index, key] = dictionary.get(key)

3
投票

上述答案具有正确的缩进

def update_row_with_dict(df,d,idx):
    for key in d.keys():
        df.loc[idx, key] = d.get(key)

再短一点就可以了

def update_row_with_dict(df,d,idx):
    df.loc[idx,d.keys()] = d.values()

对于您的代码片段,语法将是:

import pandas as pd    
import numpy as np

dataframe = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9], [4, 6, 2], [3, 4, 1]])
dataframe.columns = ['x', 'y', 'z']
additional_cols = ['a', 'b', 'c']

for col in additional_cols:
    dataframe[col] = np.nan

for idx in dataframe.index:
    y = {'a':1,'b':2,'c':3}
    update_row_with_dict(dataframe,y,idx)
© www.soinside.com 2019 - 2024. All rights reserved.