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

2024-06-01 02:47:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将数据帧中不同行中的列连接起来。你知道吗

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学习者。我做了一些研究,一直到这里。请帮我弄清楚确切的方法。你知道吗


Tags: 数据importdataframepandasdfdataasnan
1条回答
网友
1楼 · 发布于 2024-06-01 02:47:49

似乎需要^{}来删除NaN,然后转换为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

相关问题 更多 >