itertuples() iterator 함수를 사용하여 pandas 테이블을 반복합니다. 조건이 참일 때 다른 열에 값을 설정하고 싶습니다. 그게 쉽지. 그러나 이전에 설정 한 값을 기반으로 다른 값을 다시 설정하고 싶지 않습니다. 두 번째로 반복해야하지만 비효율적입니다. 하나의 반복 프로세스 내에서 다른 열에 여러 값을 설정할 수 있습니까? 나는 가득 코멘트 열을 얻는 대신 다른 반복을 할 필요가팬더 테이블에서 한 번만 반복하여 여러 값을 설정하는 방법은 무엇입니까?
data = {
'Animal': ['cat', 'dog', 'dog', 'cat', 'bird', 'dog', 'cow'],
'Noise': ['muh', 'miau', 'wuff', 'piep', 'piep', 'miau', 'muh']
}
df = pd.DataFrame(data)
df.insert(loc=2, column='Match', value='')
df.insert(loc=3, column='Comment', value='')
for row in df.itertuples():
if row.Animal == 'cat' and row.Noise == 'miau':
df.set_value(index=row.Index, col='Match', value=True)
elif row.Animal == 'dog' and row.Noise == 'wuff':
df.set_value(index=row.Index, col='Match', value=True)
elif row.Animal == 'bird' and row.Noise == 'piep':
df.set_value(index=row.Index, col='Match', value=True)
elif row.Animal == 'cow' and row.Noise == 'muh':
df.set_value(index=row.Index, col='Match', value=True)
# Why is this not getting applied to the 'Comment' column?
if row.Match is True:
df.set_value(index=row.Index, col='Comment', value='yeah')
: 여기
몇 가지 예제 코드입니다for row in df.itertuples():
if row.Match is True:
df.set_value(index=row.Index, col='Comment', value='yeah')
그러나 즉 500000+ 값이 매우 비효율적이며, 시간이 많이 걸린다. 그런 식으로하는 더 좋은 방법은 무엇일까요?
왜 같은 루프에서 사용하지 않습니까? 항상 같은 시간에 설정하는 것 같습니다 – marisbest2
또한 하나의 조건부를 사용하고 '또는'을 사용하는 것을 고려하십시오. 그런 식으로 반복 코드 – marisbest2
을 반복 할 필요가 없습니다. 동일한 루프에서 작동하지 않기 때문입니다. 이것은 정확히 같은 루프에서 불가능한 이유입니다. ;-) – qfactor