티스토리 뷰
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
'개발 > 파이썬' 카테고리의 다른 글
Pandas에서 SettingWithCopyWarning을 처리하는 방법 (0) | 2022.12.07 |
---|---|
기존 Pandas 데이터 프레임에 새 열을 추가하기 (0) | 2022.12.07 |
Pandas DataFrame 열 전체 리스트 가져오기 (0) | 2022.12.06 |
데이터 프레임 열 순서 변경하기 (0) | 2022.12.06 |
Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session' 에러 수정하기 (0) | 2022.12.06 |