[英]Replace python pandas df with values of a second dataframe based with condition
I am new to python as I normally write scripts in R and therefore am learning to adjust to Pandas dataframes and nuances. 我是python的新手,因为我通常在R中编写脚本,因此我正在学习如何适应Pandas数据帧和细微差别。
I have two lists of dicts that I turned into dataframes as I thought it would be easier to work with in that format. 我有两个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}]
I then put these as dataframes: 然后我将这些作为数据帧:
df1new = DataFrame(df1, columns=['test', '25th_percentile', 'mean', '50th_percentile','75th_percentile'])
df2new = DataFrame(df2)
Now, I would like to replace the contents of the column 'mean' in df1new if 'test' == "ACT Composite" and 'mean' is None 现在,如果'test'==“ACT Composite”并且'mean'为None,我想替换df1new中'mean'列的内容
I have tried to use a combine_first approach, however I believe this requires the dataframes to be more similarly indexed. 我曾尝试使用combine_first方法,但我相信这需要对数据帧进行更类似的索引。 I have also tried: 我也尝试过:
if df1new['test'] == "ACT Composite" and df1new['mean'] == None:
df1new['mean'] == df2new['mean']
as well as a .replace() variation. 以及.replace()变体。
Any advice would be greatly appreciated! 任何建议将不胜感激! Thank you in advance! 先感谢您!
maybe this: 也许这个:
idx = (df1new.test == 'ACT Composite') & df1new['mean'].isnull()
df1new['mean'][idx] = df2new['mean'][1]
I added a [1]
up there because i suppose that is what you want, the mean
value corresponding to ACT Composite
in df2new
. 我加了[1]
在那里,因为我想这是你想要什么,在mean
对应值ACT Composite
的df2new
。 it could also be written as 它也可以写成
df1new['mean'][idx] = df2new['mean'][df2new.test == 'ACT Composite']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.