【问题标题】:How to select columns from different tables based on other facture to create a new dataframe python如何根据其他事实从不同表中选择列以创建新的数据框python
【发布时间】:2021-02-13 18:18:41
【问题描述】:

我有 2 个 DataFrames 两个国家 1-先有183行 2-第二个有 156 行 他们都有彼此的进口信息 我需要第一列中的一列和第二列中的一列 我的目标是创建一个单独的 Dataframe,其中包含我需要的两个列以及两个 datafames commo 所包含的名称。

这就是我所做的以及我得到的信息

for i in range(183) :
    for j in range(156):
        if df['Country'][i]==df_happy['Country or region'][j]:
            df.drop(i,axis=0,inplace=True) 
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-25-e078ef71e219> in <module>
      1 for i in range(183) :
      2     for j in range(156):
----> 3         if df['Country'][i]==df_happy['Country or region'][j]:
      4             df.drop(i,axis=0,inplace=True)

/opt/conda/envs/Python-3.7-main/lib/python3.7/site-packages/pandas/core/series.py in __getitem__(self, key)
    869         key = com.apply_if_callable(key, self)
    870         try:
--> 871             result = self.index.get_value(self, key)
    872 
    873             if not is_scalar(result):

/opt/conda/envs/Python-3.7-main/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_value(self, series, key)
   4403         k = self._convert_scalar_indexer(k, kind="getitem")
   4404         try:
-> 4405             return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))
   4406         except KeyError as e1:
   4407             if len(self) > 0 and (self.holds_integer() or self.is_boolean()):

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 1

【问题讨论】:

    标签: python pandas dataframe data-science data-analysis


    【解决方案1】:

    您可以合并两个数据框:

    newdf=df.merge(df_happy,how='left', left_on='Country', right_on='Country or region')
    

    然后删除多余的列:

    newdf.drop(columns=['B', 'C'])
    

    【讨论】:

      猜你喜欢
      • 2017-01-03
      • 1970-01-01
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多