簡體   English   中英

pandas將一系列映射到另一個系列,由2列數據幀組成

[英]pandas map a series to another series by 2 columns of a dataframe

假設我有一個包含2列的數據框:

indexes = pd.Series(np.arange(10))
np.random.seed(seed=42)
values = pd.Series(np.random.normal(size=10))
df = pd.DataFrame({"unique_col": indexes, "value": values})

# df:
   unique_col     value
0           0  0.496714
1           1 -0.138264
2           2  0.647689
3           3  1.523030
4           4 -0.234153
5           5 -0.234137
6           6  1.579213
7           7  0.767435
8           8 -0.469474
9           9  0.542560

我想將這個系列映射到這個數據幀:

uniq = pd.Series([1,3,5,6], index=[20, 45, 47, 51], name="unique_col")

# uniq
20    1
45    3
47    5
51    6
Name: unique_col, dtype: int64

uniq系列有特殊的索引,我不想丟失。 unique_col在這里是int ,但在我的真實世界中,它是一個復雜而獨特的字符串。

我想映射unique_col並提取value ,我目前這樣做:

uniqdf = pd.DataFrame(uniq)
mergedf = pd.merge(uniqdf, df, on="unique_col", how="left").set_index(uniq.index)
myresult = mergedf["value"]

# myresult
20   -0.138264
45    1.523030
47   -0.234137
51    1.579213
Name: value, dtype: float64

這有必要嗎? 有沒有更簡單的方法不涉及pd.merge和從Series轉換為DataFrame

這是你需要的嗎?

s=df.set_index('unique_col').value.reindex(uniq).values
pd.Series(s,index=uniq.index)
Out[147]: 
20   -0.138264
45    1.523030
47   -0.234137
51    1.579213
dtype: float64

只需使用map

uniq.map(df.set_index('unique_col')['value'])

20   -0.138264
45    1.523030
47   -0.234137
51    1.579213
Name: unique_col, dtype: float64

暫無
暫無

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

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