![](/img/trans.png)
[英]Select rows from pandas dataframe by two values at the same time from rows in another dataframe
[英]Use two rows from a pandas dataframe to select a location in another dataframe
我有第一个数据帧df1
如下。 这里col_b
是 h1 和 h24 之间的任何数字,并且不包含每个相应日期的所有 1 到 24:
Date col_b
20101101 h1
20101101 h2
20101101 h3
20101102 h1
20101102 h3
20101103 h2
20101104 h1
20101105 h2
20101105 h3
20101106 h6
20101106 h8
20101106 h24
20101107 h15
第二个数据帧df2
为:
date h1 h2 h3 h4 h5 h6 ... h24
20101101 4 6 45 6 7 8 ... 5
20101102 .........................
20101103 .........................
我需要从df2
选择值到一个列表,其中df1
中的行与df2
的位置匹配。
目前,我使用iterrows
选择从行值df1
和分配在值df2
作为df2.loc[df2['Date] ==row[0], row[1]]
在每个行df1
。
这是忙碌的,消耗大量时间。 有没有 pythonic 或 Pandas 的方法来做到这一点?
使用DataFrame.lookup()
:
import numpy as np
import pandas as pd
df2 = pd.DataFrame(np.random.randint(0, 10, (5, 3)),
columns=list("ABC"),
index=pd.date_range("2016/01/01", "2016/05/01", freq="MS"))
df = pd.DataFrame({"date":df2.index[np.random.randint(0, 5, 10)],
"key": df2.columns[np.random.randint(0, 3, 10)]})
df["value"] = df2.lookup(df["date"], df["key"])
print(df)
结果:
date key value
0 2016-01-01 C 2
1 2016-05-01 A 8
2 2016-01-01 A 8
3 2016-04-01 B 1
4 2016-04-01 C 2
5 2016-03-01 A 2
6 2016-03-01 A 2
7 2016-04-01 B 1
8 2016-05-01 A 8
9 2016-03-01 B 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.