【问题标题】:Python pandas concatenate columns csvPython pandas连接列csv
【发布时间】:2019-05-19 09:16:24
【问题描述】:

我有一大串 Users_id 想要连接。我知道如何在 excel 中执行此操作,但文件太大了。

Users ID    
101 101
102 101,102
103 101,102,103
104 101,102,103,104

这就是我想要实现的目标。这是我目前所拥有的。

import pandas as pd

df = pd.read_csv('file.csv')

pd.concat = df['USER ID']=.astype(str)+','+df['USER ID']

【问题讨论】:

  • 你想要的输出是什么?

标签: python pandas csv concatenation


【解决方案1】:

这是一个不寻常的操作,因为您的输入是数字,而您的输出是逗号分隔的字符串序列。一种解决方案是将 itertools.accumulate 与 f 字符串一起使用(Python 3.6;PEP498):

import pandas as pd
from itertools import accumulate

df = pd.DataFrame({'Users': [101, 102, 103, 104]})

def joiner(x, y):
    return f'{x},{y}'

df['Cumulative'] = list(accumulate(df['Users'].astype(str), func=joiner))

print(df)

   Users       Cumulative
0    101              101
1    102          101,102
2    103      101,102,103
3    104  101,102,103,104

【讨论】:

    【解决方案2】:

    我不明白你的代码。 如果要连接所有用户 ID,则应遍历 ID 列并手动连接所有 ID。下面的代码应该这样做

    id_column=df['ID']
    all_ids=''
    for id in id_column:
        all_ids+=str(id)+','
    

    所有的 ID 都应该包含在变量 all_ids 中。

    【讨论】:

    • 如果这是 OP 想要的,那么','.join(df['ID'].astype(str)) 就足够了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 2018-04-20
    相关资源
    最近更新 更多