在dataframe python中组合不同行中的列

问题描述 投票:1回答:1

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

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个回答
0
投票

看来你需要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
© www.soinside.com 2019 - 2024. All rights reserved.