빈 데이터 프레임을 만들고 열에 하나의 문자열 값을 추가하려고 시도했지만 비어 있음
import pandas as pd
df = pd.DataFrame()
df['Man'] = "manish"
print(df)
위의 코드를 실행할 때 다음과 같이 출력됩니다.
Empty DataFrame
Columns: [Man]
Index: []
내가 코드 아래에서 실행할 때
df['Man'] = ['manish']
print(df)
내가 예상했던 올바른 출력을 얻고 있습니다.
Man
0 manish
아무도 왜 이런 일이 일어나는지 설명 할 수 있습니까?
함수에 쓰여진 것처럼 value와 같은 목록을__setitem__
기대하는 코드를 살펴보면 다음과 같습니다_ensure_valid_index
.
def _ensure_valid_index(self, value):
"""
Ensure that if we don't have an index, that we can create one from the
passed value.
"""
# GH5632, make sure that we are a Series convertible
if not len(self.index) and is_list_like(value):
try:
value = Series(value)
except (ValueError, NotImplementedError, TypeError):
raise ValueError(
"Cannot set a frame with no defined index "
"and a value that cannot be converted to a "
"Series"
)
self._data = self._data.reindex_axis(
value.index.copy(), axis=1, fill_value=np.nan
)
따라서 인덱스의 len이 0이면 (귀하의 경우와 같이) 문자열이 아닌 값과 같은 목록을 기대하여 Series로 변환하고 거기에서 인덱스를 사용하십시오. 함수 _ensure_valid_index
는 내부에서 호출됩니다 set_item
.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다