티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Create a Pandas Dataframe by appending one row at a time

한 번에 하나의 행을 추가하여 Pandas 데이터 프레임 만들기

 문제 내용 

How do I create an empty DataFrame, then add rows, one by one?

빈 데이터 프레임을 만든 다음 행을 하나씩 추가하려면 어떻게 해야 합니까?

 

I created an empty DataFrame:

빈 데이터 프레임을 만들었습니다.
df = pd.DataFrame(columns=('lib', 'qty1', 'qty2'))

 

Then I can add a new row at the end and fill a single field with:

그런 다음 끝에 새 행을 추가하고 단일 필드를 다음과 같이 채울 수 있습니다.
df = df._set_value(index=len(df), col='qty1', value=10.0)

 

It works for only one field at a time. What is a better way to add new row to df?

한 번에 한 필드에만 적용됩니다. df에 새 행을 추가하는 더 좋은 방법은 무엇입니까?

 

 

 

 높은 점수를 받은 Solution 

You can use df.loc[i], where the row with index i will be what you specify it to be in the dataframe.

df.loc[i]를 사용할 수 있습니다. 여기서 인덱스 i가 있는 행은 데이터 프레임에 지정된 행이 됩니다.
>>> import pandas as pd
>>> from numpy.random import randint

>>> df = pd.DataFrame(columns=['lib', 'qty1', 'qty2'])
>>> for i in range(5):
>>>     df.loc[i] = ['name' + str(i)] + list(randint(10, size=2))

>>> df
     lib qty1 qty2
0  name0    3    3
1  name1    2    4
2  name2    2    8
3  name3    2    1
4  name4    9    6

 

 

 가장 최근 달린 Solution 

If you always want to add a new row at the end, use this:

항상 끝에 새 행을 추가하려면 다음을 사용하세요.
df.loc[len(df)] = ['name5', 9, 0]

 

 

출처 : https://stackoverflow.com/questions/10715965/create-a-pandas-dataframe-by-appending-one-row-at-a-time

반응형
댓글
공지사항
최근에 올라온 글