熊猫:无法通过单个字符串更新空数据框

时间:2019-11-14 20:50:54

标签: python pandas list dataframe

我创建了一个空的数据框,并尝试将一个字符串值添加到列中,但是它显示为空

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

谁能解释我为什么会这样?

1 个答案:

答案 0 :(得分:1)

通过查看__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为零(如您的情况),则它期望像值之类的列表(不是字符串)将其转换为Series并从那里使用索引。函数_ensure_valid_indexset_item内部被调用。