[英]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.