【问题标题】:How to combine 2 columns with different names to fill the nulls of the first with the values of the second?如何组合具有不同名称的 2 列以用第二个的值填充第一个的空值?
【发布时间】:2020-05-24 22:42:46
【问题描述】:

我有这个 df:

           country  customer_id   invoice   price   stream_id   times_viewed    year    month   day total_price StreamID    TimesViewed
0   United Kingdom  13085.0        489434    6.95       85048           12.0    2017       11   28          NaN      NaN            NaN
1   United Kingdom  NaN            489597    8.65       22130            1.0    2017       11   28          NaN      NaN            NaN
2   United Kingdom  NaN            489597    1.70       22132            6.0    2017       11   28          NaN     NaN              NaN
3   United Kingdom  NaN            489597    1.70       22133            4.0    2017       11   28          NaN     NaN             NaN
4   United Kingdom  NaN            489597    0.87       22134            1.0    2017       11   28          NaN     NaN             NaN

stream_idStreamID 列实际上是同一个东西。我拥有的 df 要大得多,它是由块创建的。问题来了,当读取这些块时,其中一些列名为stream_id,而另一些列名为StreamID,因此当使用pd.concat 将所有块放在一起时,最终结果如下所示。

当最后一个不为空时,我想做的是用stream_id 的值填充StreamID 的空值。我不确定这是否是正确的方法,或者是否有更有效的方法来解决这个问题。

times_viewedTimesViewed 列也出现了同样的问题,因此同样的解决方案也适用于这一列。

我尝试像这样使用np.where

df['new_col'] = np.where(df['StreamID'].isnull(), df['stream_id'], df['StreamID'])

但我不确定这是否正确,或者是否有更好的方法来做到这一点。有人可以帮我解决这个问题吗?

非常感谢您。

【问题讨论】:

  • 我认为最好在连接之前重命名列以避免此问题,而不是 np.wheredf.loc 填充空值然后删除重复的列。跨度>
  • 嗨@Datanovice。是的,我知道,但是我从许多单独的 json 文件中组成了这个 df,找出哪些文件具有哪些列名会很痛苦。是因为我正在寻找另一种方法来解决这个问题。 np.wheredf.iloc 你会怎么做?
  • are the columns ordered, just rename them according to order, or use index=False` in pd.concat 沿顶轴连接

标签: python python-3.x pandas dataframe null


【解决方案1】:

我终于通过在检查它们是否存在后逐步重命名错误的列名来解决它,然后将从每个文件创建的每个 df 添加到最后连接的临时列表中,给出最终结果:

import glob
import pandas as pd

files = sorted(glob.glob(os.getcwd() + "/data_dir/*.json"))

df_list = []

for i in files:

    temp_df = pd.read_json(i)

    if 'StreamID' in temp_df.columns or 'total_price' in temp_df.columns or 'TimesViewed' in temp_df.columns:

        temp_df.rename(columns = {'StreamID': 'stream_id', 'total_price': 'price', 'TimesViewed': 'times_viewed'}, inplace = True)

    df_list.append(temp_df)

df = pd.concat(df_list, axis = 0)

它完全解决了名称错误的重复列的问题。希望这会对某人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-30
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多