【问题标题】:Fill up another column based on another columns unique value根据另一列唯一值填充另一列
【发布时间】:2021-03-16 07:38:05
【问题描述】:

我有这个 csv 数据(一个例子):

我有 5000 个邮政编码以及其他列,但其中 34 个(邮政编码)是唯一的。我必须获取每个邮政编码并点击另一个 API 才能获得收入中位数,但是如何用重复的邮政编码填写另一行的收入中位数列?

注意:没有找到与我的案子有关的任何东西。

【问题讨论】:

  • 对不起,我真的不明白你想要做什么,你能改一下吗?是否要复制 ZIP 列?您想获取唯一值吗?
  • 这个其他 API 的输出是什么?字典?
  • @OliverHnat 假设我得到 34 个唯一邮政编码的收入中位数,但我想用我得到的值填写重复邮政编码的收入中位数。
  • @CainãMaxCouto-Silva 其实没问题。

标签: python pandas dataframe


【解决方案1】:

您希望我们 transform,它返回一个 DataFrame,其索引与填充转换值的原始对象相同。

您需要编写一个函数,该函数采用邮政编码并返回中间值。看这个例子:

import pandas as pd

def get_med(zip_code):
    # This would be your get call to the API
    # Here, `zip_code` is a Series, use `.iloc[0]` 
    # to get the value of the group 
    return zip_code.iloc[0] * 100

df = pd.DataFrame({"zip":[1, 2, 3, 1, 1]})
df["med_income"] = df.groupby("zip")["zip"].transform(get_med)
#    zip  med_income
# 0    1         100
# 1    2         200
# 2    3         300
# 3    1         100
# 4    1         100

或者,您可以在 dict 中生成所有中间值,然后将 map 返回到 DataFrame:

medians = {get_median(zip_code) for zip_code in df["zip"].unique()}
df["med_income"] = df["zip"].map(medians)

【讨论】:

    【解决方案2】:

    我相信您正在寻找熊猫map。所以让我们假设第二个 API 的输出是一个字典(也许你可以设法得到它):

    # Get unique zip codes to use as input to the API
    zip_codes = df['Zip'].unique()
    
    # Let's suppose you get an ouput like this
    zip_dict = {46234: 1500, 46250: 2000, 46280: 1200} # and so on...
    

    因此,您可以像这样将邮政编码映射到收入中位数:

    df['Median Income'] = df['Zip'].map(zip_dict)
    

    df 是您的数据框。

    【讨论】:

    • 另外,另一种选择是将输出(作为包含“Zip”和“中值收入”列的数据框)与df 合并。不过,使用map 更简单。
    【解决方案3】:

    据我了解,您想获取邮政编码的唯一值吗?如果是,那么您可以使用

    df.yourColumn.unique()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 2020-11-26
      • 2022-01-15
      • 1970-01-01
      相关资源
      最近更新 更多