繁体   English   中英

使用字典替换 Pandas 数据帧上给定索引号的列值

[英]Using a dictionary to replace column values on given index numbers on a pandas dataframe

考虑以下数据框

df_test = pd.DataFrame( {'a' : [1, 2, 8], 'b' : [np.nan, np.nan, 5], 'c' : [np.nan, np.nan, 4]})
df_test.index = ['one', 'two', 'three']

这使

      a  b   c
one   1 NaN NaN
two   2 NaN NaN
three 8  5   4

我有一个列 b 和 c 的行替换字典。 例如:

{ 'one': [3.1, 2.2], 'two' : [8.8, 4.4] }

其中 3.1 和 8.8 替换 b 列,2.2 和 4.4 替换 c 列,因此结果为

      a  b   c
one   1 3.1 2.2
two   2 8.8 4.4
three 8  5   4

我知道如何使用 for 循环进行这些更改:

index_list = ['one', 'two']
value_list_b = [3.1, 8.8]
value_list_c = [2.2, 4.4]
for i in range(len(index_list)):
    df_test.ix[df_test.index == index_list[i], 'b'] = value_list_b[i]
    df_test.ix[df_test.index == index_list[i], 'c'] = value_list_c[i]

但我相信有一种更好更快的方式来使用字典!

我想它可以用DataFrame.replace方法完成,但我无法弄清楚。

谢谢您的帮助,

光盘

您正在寻找pandas.DataFrame.update 在您的情况下唯一的扭曲是您将更新指定为行字典,而 DataFrame 通常是从列字典构建的。 orient关键字可以解决这个问题。

In [24]: import pandas as pd

In [25]: df_test
Out[25]: 
       a   b   c
one    1 NaN NaN
two    2 NaN NaN
three  8   5   4

In [26]: row_replacements = { 'one': [3.1, 2.2], 'two' : [8.8, 4.4] }

In [27]: df_update = pd.DataFrame.from_dict(row_replacements, orient='index')

In [28]: df_update.columns = ['b', 'c']

In [29]: df_update
Out[29]: 
        b     c
one   3.1   2.2
two   8.8   4.4

In [30]: df_test.update(df_update)

In [31]: df_test
Out[31]: 
       a    b    c
one    1  3.1  2.2
two    2  8.8  4.4
three  8  5.0  4.0

pandas.DataFrame.from_dict是一个特定的 DataFrame 构造函数,它为我们提供orient关键字,如果您只说DataFrame(...)则不可用。 由于我不知道的原因,我们不能将列名['b', 'c']传递给from_dict ,所以我在单独的步骤中指定了它们。

暂无
暂无

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

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