1
나는이 같은 dataframe 가지고 함수 return_something(pref)
을 사용하여 각 행의 색인 지금은 구현이 다음과 같이 : 다음 나에게 원하는 출력을 제공한다는가장 효율적인 방법은
import pandas as pd
import numpy as np
# this just returns a random value for the sake of simplicity
def return_something(pref):
return np.random.choice(len(pref)+10)
df = pd.DataFrame(index=['pre1_xyz', 'pre1_foo', 'pre3_bar', 'pre3_foo', 'pre10_foo', 'pre10_bar', 'pre10_xyz'])
# get all the unique prefixes
unique_pref = set([pi.partition('_')[0] for pi in df.index])
# determine the value for each prefix
val_pref = {pref: return_something(pref) for pref in unique_pref}
# add the values to the dataframe
for prefi, vali in val_pref.items():
# determine all rows with the same prefix
rows = [rowi for rowi in df.index if rowi.startswith(prefi+'_')]
df.loc[rows, 'values'] = vali
:
values
pre1_xyz 0
pre1_foo 0
pre3_bar 7
pre3_foo 7
pre10_foo 13
pre10_bar 13
pre10_xyz 13
질문은 무엇이든이, 예를 들어보다 똑똑 존재 여부 unique_pref
및/또는 val_pref
을 생성하지 않고 this question에서 논의 된 것처럼 데이터 프레임에 값을 추가하는 가장 빠른 솔루션 인 것처럼 보이는 set_value
을 사용하는 솔루션입니다.
잘 작동합니다. 위로 upvoted. – Cleb
@ 클리블은 문제를 해결 한 경우 답변으로 표시하는 것을 고려합니다. – piRSquared
@ piRSquared : 나는 더 나은 것이 나타나지 않으면, 할 것이다. 때로는 더 나은 해결책이 나오기 때문에 나는 보통 받아 들일 때까지 잠시 기다린다. 내 프로필을 보면, (좋은) 답변이 있으면 항상 대답을 수락한다는 것을 알 수 있습니다. – Cleb