在 Python 3.10 中使用 concat 将字典添加到 Pandas DataFrame 中的一行
Adding a dictionary to a row in a Pandas DataFrame using concat in Python 3.10
更新到 Python 3.10 后,我现在在使用 frame.append 将字典附加到 Pandas DataFrame 时收到以下警告。
FutureWarning: The frame.append method is deprecated and will be
removed from pandas in a future version. Use pandas.concat instead.
下面是代码。这仍然有效,但我想解决警告。
report = report.append({
"period":period,
"symbol":symbol,
"start_date":start_date,
"start_price":start_price,
"start_market_cap":start_market_cap,
"end_date":end_date,
"end_price":end_price,
"end_market_cap":end_market_cap,
"return":return_
},ignore_index=True)
我已将代码更新为以下内容,这会引发不同的警告:
report = pd.concat([report,{
"period":period,
"symbol":symbol,
"start_date":start_date,
"start_price":start_price,
"start_market_cap":start_market_cap,
"end_date":end_date,
"end_price":end_price,
"end_market_cap":end_market_cap,
"return":return_
}],ignore_index=True)
TypeError: cannot concatenate object of type '<class 'dict'>'; only Series and DataFrame objs are valid
2个问题:
第一个警告是错误的吗?
3.10 的实现方式是什么?
谢谢。
使用loc
分配单行值:
report.loc[len(report)] = {"period":period,
"symbol":symbol,
"start_date":start_date,
"start_price":start_price,
"start_market_cap":start_market_cap,
"end_date":end_date,
"end_price":end_price,
"end_market_cap":end_market_cap,
"return":return_
}
更新到 Python 3.10 后,我现在在使用 frame.append 将字典附加到 Pandas DataFrame 时收到以下警告。
FutureWarning: The frame.append method is deprecated and will be
removed from pandas in a future version. Use pandas.concat instead.
下面是代码。这仍然有效,但我想解决警告。
report = report.append({
"period":period,
"symbol":symbol,
"start_date":start_date,
"start_price":start_price,
"start_market_cap":start_market_cap,
"end_date":end_date,
"end_price":end_price,
"end_market_cap":end_market_cap,
"return":return_
},ignore_index=True)
我已将代码更新为以下内容,这会引发不同的警告:
report = pd.concat([report,{
"period":period,
"symbol":symbol,
"start_date":start_date,
"start_price":start_price,
"start_market_cap":start_market_cap,
"end_date":end_date,
"end_price":end_price,
"end_market_cap":end_market_cap,
"return":return_
}],ignore_index=True)
TypeError: cannot concatenate object of type '<class 'dict'>'; only Series and DataFrame objs are valid
2个问题: 第一个警告是错误的吗? 3.10 的实现方式是什么? 谢谢。
使用loc
分配单行值:
report.loc[len(report)] = {"period":period,
"symbol":symbol,
"start_date":start_date,
"start_price":start_price,
"start_market_cap":start_market_cap,
"end_date":end_date,
"end_price":end_price,
"end_market_cap":end_market_cap,
"return":return_
}