向pandas DataFrame对象添加空列的最简单方法是什么?我碰到的最好的是
df['foo'] = df.apply(lambda _: '', axis=1)
有没有更合理的方法?
向pandas DataFrame对象添加空列的最简单方法是什么?我碰到的最好的是
df['foo'] = df.apply(lambda _: '', axis=1)
有没有更合理的方法?
当前回答
我喜欢:
df['new'] = pd.Series(dtype='int')
# or use other dtypes like 'float', 'object', ...
如果您有一个空的数据框架,这个解决方案确保没有只包含NaN的新行被添加。
指定dtype并不是必须的,但是如果没有指定dtype,更新的Pandas版本会产生DeprecationWarning。
其他回答
很抱歉我一开始没有解释清楚我的答案。还有另一种方法可以将新列添加到现有数据框架中。 第一步,创建一个新的空数据帧(包含数据帧中的所有列,加上您想添加的新列或少数列),称为df_temp 第二步,结合df_temp和你的数据帧。
df_temp = pd.DataFrame(columns=(df_null.columns.tolist() + ['empty']))
df = pd.concat([df_temp, df])
这可能是最好的解决方案,但这是思考这个问题的另一种方式。
我使用这种方法的原因是因为我总是得到这样的警告:
: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
df["empty1"], df["empty2"] = [np.nan, ""]
太好了,我找到了禁用警告的方法
pd.options.mode.chained_assignment = None
我喜欢:
df['new'] = pd.Series(dtype='int')
# or use other dtypes like 'float', 'object', ...
如果您有一个空的数据框架,这个解决方案确保没有只包含NaN的新行被添加。
指定dtype并不是必须的,但是如果没有指定dtype,更新的Pandas版本会产生DeprecationWarning。
你可以这样做
df['column'] = None #This works. This will create a new column with None type
df.column = None #This will work only when the column is already present in the dataframe
@emunsing的回答非常酷,可以添加多列,但我在python 2.7中无法让它为我工作。相反,我发现这个方法很有效:
mydf = mydf.reindex(columns = np.append( mydf.columns.values, ['newcol1','newcol2'])
从v0.16.0开始,可以使用DF.assign()将新列(单个/多个)分配给DF。这些列按字母顺序插入DF的末尾。
当你想直接对返回的数据帧执行一系列链式操作时,这比简单的赋值更有优势。
考虑@DSM演示的相同DF示例:
df = pd.DataFrame({"A": [1,2,3], "B": [2,3,4]})
df
Out[18]:
A B
0 1 2
1 2 3
2 3 4
df.assign(C="",D=np.nan)
Out[21]:
A B C D
0 1 2 NaN
1 2 3 NaN
2 3 4 NaN
请注意,这将返回一个副本,其中包含所有以前的列以及新创建的列。为了对原始DF进行相应的修改,可以这样使用:DF = DF .assign(…),因为它目前不支持就地操作。