如何将 pandas 系列的列值转换为 Python 中的列表?
How to convert the column values of pandas series to list in Python?
我有一个 pandas 系列,打印后看起来像 -
0 NaN
1 20.307
2 -16.879
3 4.598
4 21.978
5 -12.913
dtype: float64
我想将第二列中的值转换为列表,使其看起来像 -
[0, 20.307, -16.879, 4.598, 21.978, -12.913]
我试过 - my_series.iloc[:, 1]
但我收到错误 -
pandas.core.indexing.IndexingError: Too many indexers
有人可以帮忙吗?谢谢。
如果使用 iloc[:, 1]
,它需要 select 第二列,但 Series
中没有列,因此引发错误。
如果想要 select 所有值而不首先使用索引 [1:]
:
L = my_series.iloc[1:].tolist()
或通过Series.dropna
删除缺失值:
L = my_series.dropna().tolist()
或将NaN
替换为0
为Series.fillna
:
L = my_series.fillna(0).tolist()
您可以使用 Series.fillna()
:
In [2640]: my_series.fillna(0).tolist()
Out[2640]: [0.0, 20.307, -16.879, 4.598, 21.978, -12.913]
让我们试试
list(df.my_series.fillna(0))
正如我从您的预期结果中看到的那样,您不想
只是删除 NaN 元素而不是转换它们
至 0.
所以为了得到你想要的结果,运行:
result = my_series.fillna(0).tolist()
我有一个 pandas 系列,打印后看起来像 -
0 NaN
1 20.307
2 -16.879
3 4.598
4 21.978
5 -12.913
dtype: float64
我想将第二列中的值转换为列表,使其看起来像 -
[0, 20.307, -16.879, 4.598, 21.978, -12.913]
我试过 - my_series.iloc[:, 1]
但我收到错误 -
pandas.core.indexing.IndexingError: Too many indexers
有人可以帮忙吗?谢谢。
如果使用 iloc[:, 1]
,它需要 select 第二列,但 Series
中没有列,因此引发错误。
如果想要 select 所有值而不首先使用索引 [1:]
:
L = my_series.iloc[1:].tolist()
或通过Series.dropna
删除缺失值:
L = my_series.dropna().tolist()
或将NaN
替换为0
为Series.fillna
:
L = my_series.fillna(0).tolist()
您可以使用 Series.fillna()
:
In [2640]: my_series.fillna(0).tolist()
Out[2640]: [0.0, 20.307, -16.879, 4.598, 21.978, -12.913]
让我们试试
list(df.my_series.fillna(0))
正如我从您的预期结果中看到的那样,您不想 只是删除 NaN 元素而不是转换它们 至 0.
所以为了得到你想要的结果,运行:
result = my_series.fillna(0).tolist()