简体   繁体   English

如何在不使用迭代的情况下从另一个 df 获取具有特定索引、列的值列表?

[英]How can I get list of values with specific index, column from another df without using iteration?

I have two dataframes df1, df2.我有两个数据框 df1、df2。

df1=pd.DataFrame(columns=['name','yr'])
df1.name=['a','b','c','b','d','a']
df1.yr=[2017,2016,2017,2018,2018,2019]
df2=pd.DataFrame(index=[2016,2017,2018,2019],columns=['a','b','c','d'],data= np.random.randn(4,4))

What I want is add new column 'z' with values from df2, corresponding 'name' and 'year'.我想要的是添加新列“z”,其中包含来自 df2 的值、对应的“名称”和“年份”。

iteration using for statement is not my consideration.使用 for 语句的迭代不是我的考虑。

*added) 'merge' cannot be used because matching data in df1 is in index&column of df2 *添加)不能使用“合并”,因为 df1 中的匹配数据在 df2 的索引和列中

Use DataFrame.lookup :使用DataFrame.lookup

df1['z'] = df2.lookup(df1['yr'], df1['name'])
print (df1)

  name    yr         z
0    a  2017 -0.578600
1    b  2016  0.997345
2    c  2017 -2.426679
3    b  2018 -0.866740
4    d  2018 -0.094709
5    a  2019  1.491390

暂无
暂无

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

相关问题 我怎样才能最好地使用来自另一个用于检索多个值的 df 的索引值创建一个新的 df? - How can I best create a new df using index values from another df that are used to retrieve multiple values? 如何获取列表中最大值的索引,然后使用最大值的索引从另一个列表中打印值? - How can I get the index of max values in list and then print the values from another list with max's index? 如何在不使用values或values_list的情况下从另一个QuerySet中有效地获取模型的QuerySet - How can I get efficiently QuerySet of a Model from another QuerySet without using values or values_list python:字典键作为行索引,值作为列标题。 如何使用字典引用并选择 df 中的特定值? - python: Dictionary key as row index, values as column headers. How do I refer back and select specific values in a df using a dictionary? 在Python中,如何将字典转换为df列,其中键与df.index值匹配? - In Python, how can I transform a dictionary into a df column, where the keys match the df.index values? 如何将列名从一个 df 索引到另一个 df 系列? - How to index column names from one df to another df series? Pandas - 如何使用另一个 DF 的值从没有任何“键”的大型 DF 中提取值? - Pandas - How to extract values from a large DF without any 'keys' using another DF's values? 如何使用 python 从列表中读取数据并将特定值索引到 Elasticsearch? - How can I read data from a list and index specific values into Elasticsearch, using python? 如何从pandas df中的x列中提取值,其中df中的y列== list(i) - How to extract values from x column in pandas df, where y column in df == list(i) 如何 append 使用另一个特定列作为 Python 中的索引,从目录中的每个文件中获取一列值 - How to append a column of values from each file in directory using another specific column as an index in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM