【问题标题】:Combine columns in different rows in dataframe python在数据框python中组合不同行中的列
【发布时间】:2018-02-02 13:56:27
【问题描述】:

我正在尝试连接数据框中不同行中的列。

import pandas as pd

tdf =  {'ph1': [1, 2], 'ph2': [3, 4], 'ph3': [5,6], 'ph4': [nan,nan]}

df = pd.DataFrame(data=tdf)

df

输出:

   ph1  ph2  ph3  ph4

0    1    3    5  nan

1    2    4    6  nan

我将 ph1、ph2、ph3、ph4 与以下代码结合起来:

for idx, row in df.iterrows():

        df = df[[ph1, ph2, ph3, ph4]]

        df["ConcatedPhoneNumbers"] = df.loc[0:].apply(lambda x: ', '.join(x), axis=1)

我明白了

df["ConcatPhoneNumbers"]

ConcatPhoneNumbers

1,3,5,,

2,4,6,,

现在我需要使用具有适当功能的 pandas 组合这些列。 我的结果应该是1,3,5,2,4,6

还需要去掉这些多余的逗号。

我是新的 Python 学习者。我做了一些研究并到达这里。请帮助我获得确切的方法。

【问题讨论】:

    标签: python python-2.7 pandas


    【解决方案1】:

    看来您需要stack 来删除NaNs,然后转换为intstrlist,最后是join

    tdf =  {'ph1': [1, 2], 'ph2': [3, 4], 'ph3': [5,6], 'ph4': [np.nan,np.nan]}
    
    df = pd.DataFrame(data=tdf)
    
    cols = ['ph1', 'ph2', 'ph3', 'ph4']
    s = ','.join(df[cols].stack().astype(int).astype(str).values.tolist())
    print (s)
    1,3,5,2,4,6
    

    【讨论】:

    • 非常感谢您的回复。不是真的。我需要组合这些连接的数字。我实际上需要1,3,5,2,4,6。将所有这些组合在一起后,我将删除第二行。
    • 但不确定是否理解 - 是否可以添加更多数据以进行更好的解释?
    • 数据实际上包含包含 10 位数字的电话号码。数据如下: tdf = {'ph1': [118-975-8368, 118-975-8369], 'ph2': [118-240-6465, 118-240-6469], 'ph3': ['nan ', 'nan'], 'ph4': ['nan','nan']}。我需要 118-975-8368、118-975-8369、118-240-6465、118-240-6469 作为我的输出。
    • 它不起作用。Giving ValueError: invalid literal for long() with base 10: '118-975-8368'
    • ','.join(tdf.loc[1:, 'ConcatNumbers'].astype(str).values.tolist()) 这对我有用。
    猜你喜欢
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2017-05-18
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    相关资源
    最近更新 更多