Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如果数据框列是一个列表,则提取该列表的元素会产生错误_Python_List_Dataframe - Fatal编程技术网

Python 如果数据框列是一个列表,则提取该列表的元素会产生错误

Python 如果数据框列是一个列表,则提取该列表的元素会产生错误,python,list,dataframe,Python,List,Dataframe,我希望使用以下代码提取每个列表的第0个成员: df["column"].apply(lambda x: x[0]) 但我得到了以下错误: TypeError:“float”对象不可下标 我认为问题在于一些NaNs值 您可以查看: print (df[df["column"].isnull()]) column 2 NaN 因此,您可以使用str[0]: df["column"].str[0] 样本: df = pd.DataFrame({'column':[['a','s'],

我希望使用以下代码提取每个列表的第0个成员:

df["column"].apply(lambda x: x[0])
但我得到了以下错误:

TypeError:“float”对象不可下标


我认为问题在于一些
NaN
s值

您可以查看:

print (df[df["column"].isnull()])

  column
2    NaN
因此,您可以使用
str[0]

df["column"].str[0]
样本:

df = pd.DataFrame({'column':[['a','s'],['d'], np.nan, ['s','d','f']]})
print (df)
      column
0     [a, s]
1        [d]
2        NaN
3  [s, d, f]

df['new'] = df["column"].str[0]
print (df)
      column  new
0     [a, s]    a
1        [d]    d
2        NaN  NaN
3  [s, d, f]    s
TypeError:“float”对象不可下标


如果
float
scalar
s之间的
list
s之间存在相同的错误:

df = pd.DataFrame({'column':[[4.4,7.8],[1], 4.7, [4, 7.4, 1.2]]})
print (df)
          column
0     [4.4, 7.8]
1            [1]
2            4.7
3  [4, 7.4, 1.2]
您可以检查所有非
列表
s值:

print (df[df["column"].apply(lambda x: isinstance(x, float))])

  column
2    4.7
解决方案是使用
if-else
和lambda函数:

print (df["column"].apply(lambda x: x if isinstance(x, float) else x[0]))
0    4.4
1    1.0
2    4.7
3    4.0
Name: column, dtype: float64

你能告诉我df[“column”]是什么样子吗?如果我的答案有问题,请告诉我,这样我就可以更正它。谢谢。非常感谢你,我对Python还不熟悉,你把它搞定了。列中有NaN值。你的回答很清楚。
print (df["column"].apply(lambda x: x if isinstance(x, float) else x[0]))
0    4.4
1    1.0
2    4.7
3    4.0
Name: column, dtype: float64