簡體   English   中英

將python pandas df替換為基於條件的第二個數據幀的值

[英]Replace python pandas df with values of a second dataframe based with condition

我是python的新手,因為我通常在R中編寫腳本,因此我正在學習如何適應Pandas數據幀和細微差別。

我有兩個dicts列表,我轉變為數據幀,因為我認為以這種格式更容易使用。

df1= [{u'test': u'SAT Math', u'25th_percentile': None, u'75th_percentile': None, u'50th_percentile': None, u'mean': 404}, {u'test': u'SAT Verbal', u'25th_percentile': None, u'75th_percentile': None, u'50th_percentile': None, u'mean': 355}, {u'test': u'SAT Writing', u'25th_percentile': None, u'75th_percentile': None, u'50th_percentile': None, u'mean': 363}, {u'test': u'SAT Composite', u'25th_percentile': None, u'75th_percentile': None, u'50th_percentile': None, u'mean': 1122}, {u'test': u'ACT Math', u'25th_percentile': None, u'75th_percentile': None, u'50th_percentile': None, u'mean': None}, {u'test': u'ACT English', u'25th_percentile': None, u'75th_percentile': None, u'50th_percentile': None, u'mean': None}, {u'test': u'ACT Reading', u'25th_percentile': None, u'75th_percentile': None, u'50th_percentile': None, u'mean': None}, {u'test': u'ACT Science', u'25th_percentile': None, u'75th_percentile': None, u'50th_percentile': None, u'mean': None}, {u'test': u'ACT Composite', u'25th_percentile': None, u'75th_percentile': None, u'50th_percentile': None, u'mean': None}]


df2 = [{u'test': u'SAT Composite', u'mean': 1981}, {u'test': u'ACT Composite', u'mean': 29.6}]

然后我將這些作為數據幀:

df1new = DataFrame(df1, columns=['test', '25th_percentile', 'mean', '50th_percentile','75th_percentile'])
df2new = DataFrame(df2)

現在,如果'test'==“ACT Composite”並且'mean'為None,我想替換df1new中'mean'列的內容

我曾嘗試使用combine_first方法,但我相信這需要對數據幀進行更類似的索引。 我也嘗試過:

if df1new['test'] == "ACT Composite" and df1new['mean'] == None:
            df1new['mean'] == df2new['mean']

以及.replace()變體。

任何建議將不勝感激! 先感謝您!

也許這個:

idx = (df1new.test == 'ACT Composite') & df1new['mean'].isnull()
df1new['mean'][idx] = df2new['mean'][1]

我加了[1]在那里,因為我想這是你想要什么,在mean對應值ACT Compositedf2new 它也可以寫成

df1new['mean'][idx] = df2new['mean'][df2new.test == 'ACT Composite']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM