我试图分别追加DataFrame的每一行。每行都有"系列"one_answers"标量"值。一个行示例是
row = {'col1': 1, 'col2':'blah', 'col3': pd.Series(['first', 'second'])}
当我从这个创建一个DataFrame时,它看起来像这样
df = pd.DataFrame(row)
df
col1 col2 col3
0 1 blah first
1 1 blah second
这就是我想要的。标量值是重复的,这很好。现在,我的一些行对列具有空的Series,例如:
another_row = {'col1': 45, 'col2':'more blah', 'col3': pd.Series([], dtype='object')}
当我创建一个新的DataFrame来连接两者时,像这样
second_df = pd.DataFrame(another_row)
返回一个空的DataFrame。这不是我想要的。
>>> second_df = pd.DataFrame({'col1': 45, 'col2':'more blah', 'col3': pd.Series([], dtype='object')})
>>> second_df
Empty DataFrame
Columns: [col1, col2, col3]
Index: []
>>>
我真正想要的是这样的
>>> second_df
>>>
col1 col2 col3
0 45 'more blah' NaN
或者类似的东西。基本上,我不希望整行都被扔到地板上,我希望空的Series用None或NaN或其他东西来表示。
我没有得到任何错误,也没有任何东西警告我有任何异常,所以我不知道为什么df是这样的。
您可以传递一个索引使其工作(并在第三列中获得NaN
的数据框):
another_row = {'col1': 45, 'col2':'more blah', 'col3': pd.Series([], dtype='object')}
second_df = pd.DataFrame(another_row, index=[0])
当传递所有标量和一个Series时,行数由Series的长度决定——如果长度为零,行数也为零。你可以传递单例列表而不是标量,这样行数就不再为零了:
another_row = {'col1': [45], 'col2': ['more blah'], 'col3': [np.nan]}
second_df = pd.DataFrame(another_row)
或者,像上面那样传递所有标量和索引,
another_row = {'col1': 45, 'col2': 'more blah', 'col3': np.nan}
second_df = pd.DataFrame(another_row, index=[0])
但是我可能会直接写
second_df = pd.DataFrame([[45, 'more blah', np.nan]],
columns=['col1', 'col2', 'col3'])
最后,我重新编写了代码以避免出现这个问题。我的解决方案如下:
我有一个函数do_data_stuff()
,它曾经返回熊猫系列,但现在我把它改为返回
- 一个系列如果里面有东西
Series([1, 2, 3])
- 或nan,如果是空的
np.nan
。
使用这种方法的一个副作用是,如果只传递标量,则DataFrame需要索引。"ValueError: If using all scalar values, you must pass an index"
所以我不能像这样传递index=[0]
硬编码,因为我想让DF让序列自动确定DF中的行数。
row = {'col1': 1, 'col2':'blah', 'col3': pd.Series(['first', 'second'])}
df = pd.DataFrame(row)
df
col1 col2 col3
0 1 blah first
1 1 blah second
所以我最后做的是添加一个动态索引调用。我不确定这是否是正确的python,但它对我有效。
stuff = do_data_stuff()
data = pd.DataFrame({
'col1': 45,
'col2': 'very awesome stuff',
'col3': stuff
},
index= [0] if stuff is np.nan else None
)
然后我用下面的语句连接我的dataframe:
data = pd.concat([data, some_other_df], ignore_index=True)
结果是一个如下所示的DataFrame
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({'col1': 1, 'col2':'blah', 'col3': pd.Series(['first', 'second'])})
>>> df
col1 col2 col3
0 1 blah first
1 1 blah second
>>> stuff = np.nan
>>> stuff
nan
>>> df = pd.concat([
df, pd.DataFrame(
{
'col1': 45,
'col2': 'more awesome stuff',
'col3': stuff
},
index= [0] if stuff is np.nan else None
)], ignore_index=True)
>>> df
col1 col2 col3
0 1 blah first
1 1 blah second
2 45 more awesome stuff NaN
你可以用任何东西代替np.nan
,比如""
。