다른 열의 값을 포함하여 문자열 열을 만드는 방법

Nov 15 2020

df =

car

big.yellow
small.red
small.black

  1. + + 사이의 각 행 값을 추가하고 싶습니다. 원하는 출력 :
vehicle = 'The vehicle is big.yellow mine'
vehicle = 'The vehicle is small.red mine' 
vehicle = 'The vehicle is small.black mine'
  1. 이 모든 문자열을 하나의 큰 문자열로 병합해야합니다.
final_vehicle = 'The vehicle is big.yellow mine
                 The vehicle is small.red mine
                 The vehicle is small.black mine'

그러나 실제 데이터의 행 수는 1000 개 이상입니다. 어떻게 속도를 높일 수 있습니까?

답변

2 TrentonMcKinney Nov 15 2020 at 04:57
  1. 각 행 값에 대한 문자열을 생성하는 벡터화 된 접근 방식은 다음과 같습니다.
    • pandas DataFrame 열의 모든 값에 문자열을 추가하는 방법 은 첫 번째 질문에 대답하지만 두 번째 질문에는 대답하지 않습니다.
    • df['col'] = 'string ' + df.car + ' string'
  2. 다음 중 하나를 사용하여 값을 단일 긴 문자열로 결합합니다.
    1. pandas.DataFrame.to_string 같이 final = df.veh.to_string(index=False)
    2. str.join() 같이 final = '\n'.join(df.veh.tolist())
import pandas as pd
import string  # for test data
import random  # for test data

# create test dataframe
random.seed(365)
df = pd.DataFrame({'car': [random.choice(string.ascii_lowercase) for _ in range(10000)]})

# display(df.head())
car
  v
  j
  w
  y
  e

# add the veh column as strings including the value from the car column
df['veh'] = 'The vehicle is ' + df.car + ' mine'

# display(df.head()
car                    veh
  v  The vehicle is v mine
  j  The vehicle is j mine
  w  The vehicle is w mine
  y  The vehicle is y mine
  e  The vehicle is e mine

# create a long string of all the values in veh
final = df.veh.to_string(index=False)

print(final)
The vehicle is v mine
The vehicle is j mine
The vehicle is w mine
The vehicle is y mine
The vehicle is e mine
...
MilosBijanic Nov 15 2020 at 04:39

이 코드는 아마도 문제를 해결합니다.

import pandas as pd
df = pd.DataFrame(columns=['id', 'car'])
df['car'] = ['big.yellow', 'small.red', 'small.black']
df['id'] = [1,1,1]

df['new'] = df.groupby('id')['car'].apply(lambda x: ('The vehicle is '+x + '\n').cumsum().str.strip())
df

결과 :


id  car             new
0   1   big.yellow  The vehicle is big.yellow
1   1   small.red   The vehicle is big.yellow\nThe vehicle is smal...
2   1   small.black The vehicle is big.yellow\nThe vehicle is smal...

그리고 마지막 :

df['new'][len(df)-1]

is :

'The vehicle is big.yellow\nThe vehicle is small.red\nThe vehicle is small.black'