[英]Copying locations in a Pandas dataframe to another dataframe using indexes and column headers
I have two dataframes and I want to extract values from one of them and put it in a different column based on the column info and index contained in a second dataframe(my dataframe is much larger than this, so I need it generalized), df1:我有两个数据帧,我想从其中一个数据帧中提取值,并根据第二个数据帧中包含的列信息和索引将其放在不同的列中(我的 dataframe 比这大得多,所以我需要对其进行概括),df1 :
apple banana pear value
127 3 7 4 0
157 5 15 26 0
241 16 14 31 0
365 42 17 18 0
df2: df2:
Col_Head
127 apple
157 pear
365 banana
I want df1 to look like this:我希望 df1 看起来像这样:
apple banana pear value
127 3 7 4 3
157 5 15 26 26
241 16 14 31 0
365 42 17 18 17
Convert your df2 Col_Head
column to dict with index as key, Col_Head
column as value.将您的 df2 Col_Head
列转换为 dict,索引为键, Col_Head
列为值。
Then apply()
df1
on rows and lookup by index to get expected col head from previous dict.然后在行上apply()
df1
并按索引查找以从先前的字典中获取预期的col head。 If index not found, use value
column head.如果未找到索引,则使用value
列头。
lookup = df2.to_dict()['Col_Head']
df1['value'] = df1.apply(lambda row: row[lookup.get(row.name, 'value')], axis=1)
print(df1)
apple banana pear value
127 3 7 4 3
157 5 15 26 26
241 16 14 31 0
365 42 17 18 17
I have two dataframes and I want to extract values from one of them and put it in a different column based on the column info and index contained in a second dataframe(my dataframe is much larger than this, so I need it generalized), df1:我有两个数据帧,我想从其中一个数据帧中提取值,然后根据第二个数据帧中包含的列信息和索引将其放在不同的列中(我的 dataframe 比这大得多,所以我需要它泛化),df1 :
apple banana pear value
127 3 7 4 0
157 5 15 26 0
241 16 14 31 0
365 42 17 18 0
df2: df2:
Col_Head
127 apple
157 pear
365 banana
I want df1 to look like this:我希望 df1 看起来像这样:
apple banana pear value
127 3 7 4 3
157 5 15 26 26
241 16 14 31 0
365 42 17 18 17
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.