python - 转置和连接字符串

标签 python python-3.x pandas

如何在不使用 for 循环的情况下转置和连接 pandas 数据帧?

这里是输入数据:

input_data =  pandas.DataFrame({'a': ['fruit', 'fruit', 'fruit', 'food', 'food', 'food', 'food'],
                      'b': ['banana', '', 'apple', 'rice', '', 'yam', 'chicken']})

结果输出应该是这样的:

result = pandas.DataFrame({'a': ['fruit', 'food'],
                      'b': ['banana  apple', 'rice  yam  chicken']})

这是我的 for 循环解决方案:

stuff_list = input_data.a.drop_duplicates().tolist()
result = pandas.DataFrame()

for s in stuff_list:
    step1 = input_data[input_data.a == s]
    step2 = ' '.join(step1.b.tolist())
    step3 = pandas.DataFrame({'a':[s], 'b':[step2]})
    result = result.append(step3)

print(result)

最佳答案

更像 agg

df.groupby('a',sort=False,as_index=False).agg(' '.join)
Out[539]: 
       a                  b
0  fruit      banana  apple
1   food  rice  yam chicken

关于python - 转置和连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56351417/

相关文章:

python - 想要在 python 中执行分组,其中分组的数据将进入行

python - 如何使用存储在文本文件中的python程序?

python - 按年月分组并在 Python 中查找前 N 个最小值列

python - 元类上的拦截运算符查找

python - 组织文件并将其复制到新文件夹

python - 获取 Pandas 中不包括标题的数据框行

python - 读取并检查文件中的连续单词

macos - Pillow w/Python3.3 不支持 ZLIB

python - pandas groupBy date 然后将日期和字符串过滤到新的数据框中

python - 类型错误 : unsupported operand type(s) for -: 'str' and 'str' in python 3. x python