Pandas获取具有相同行值的多列值,并将其输入到一列中

2024-10-02 08:21:17 发布

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

请查看以下示例:

import numpy as np
import pandas as pd
df_a = pd.DataFrame({ 'Type': ['A','A', 'B','B','B' 'C', 'D', 'E'], 'Values':[apple, apple,orange,orange,orange, 3,cat, 4]})
df_a

   Type Values
0   A   apple
1   A   apple
2   B   orange
3   B   orange
4   B   orange
5   C   3
6   D   cat
7   E   4

如何到达下面的数据帧。我想按列“Type”分组。然后获取与特定“Type”相关联的所有值,并将它们表示在一行中,以及它们各自的“Type”。如下图所示:

grouped = data.groupby(['Type'])

       Type      Values
    0   A      apple apple
    1   B      orange orange orange 
    2   C      3
    3   D      Cat

4和4

import pandas as pd
import numpy as np
import pyautogui as p
import pyperclip as c
import os
import sys
##
def press(key,times):
    for i in range(0,times):
        p.press(key)



df = pd.read_csv("13rp44.csv", encoding = "ISO-8859-1", dtype=object)
df.columns = df.columns.str.strip().str.replace(' ', '_').str.replace('(', '').str.replace(')', '')



for i, row in df.iterrows(): #iterate through each row with with row value and row content
    a = (row['Work_Order'])
    c.copy(a)
    b = c.paste()
    p.click(75,753)
    p.PAUSE = 5
    p.typewrite('JBA')
    press('enter',3)
    p.typewrite('2')
    p.press('enter')
    p.typewrite('40')
    p.keyDown('shift') 
    press('f4',1)
    p.keyUp('shift')
    p.typewrite('1/Iq1')
    press('enter',1)
    p.typewrite(b)
    press('enter',1)
    press('f8',1)
    press('f6',1)
    p.PAUSE = .1
    # now we will try and captue qty needed
    press('down',8)
    press('right',64)
    # works fine above, just cant figure out how to copy in values well

    p.keyDown('shift')
    p.press('c')
    p.keyUp('crl')
    b = c.paste()
    print(b)
    #p.keyDown('shift')
    #press('right',4)
    #p.keyUp('shift')
    #p.keyDown('ctrl')
    #press('c',1)
    #p.keyUp('ctrl')
    #v1 = c.paste()
    #print(v1)

    sys.exit()
    df.set_value(i, 'Test', b)

测试


Tags: importappledfshiftastyperowpd
1条回答
网友
1楼 · 发布于 2024-10-02 08:21:17

可以将groupbyjoin一起使用

df = df_a.groupby('Type').Values.apply(' '.join).reset_index()
df
Out[534]: 
  Type                Values
0    A           apple apple
1    B  orange orange orange
2    C                     3
3    D                   cat
4    E                     4

相关问题 更多 >

    热门问题