选择特定列时的值

2024-09-30 05:15:05 发布

您现在位置:Python中文网/ 问答频道 /正文

目前正在尝试收集一些关于熊猫和Matplotlib数据科学的知识

我想做什么
选择具有相应价格的邻里组租用私人房间(AirBnB)

问题
对于一列,我得到了正确的数据,但是对于其余的列,我得到了NaN值。感谢您的帮助,下面您可以找到一个代码片段和输出

    ap_df = pd.DataFrame()

for neighbourhood_group in df['neighbourhood_group'].unique():
    nbhg_df = df.copy()[df['neighbourhood_group']==neighbourhood_group]
    nbhg_df[f"{neighbourhood_group}_Price"] = nbhg_df['price']
    nbhg_df.set_index("id", inplace=True)
    nbhg_df.sort_index(inplace=True)
    if ap_df.empty:
        ap_df = nbhg_df[[f"{neighbourhood_group}_Price"]]
    else:
        ap_df = ap_df.join(nbhg_df[f"{neighbourhood_group}_Price"])

ap_df

Output I receive after performing the above Code


Tags: 数据邻里truedfindexmatplotlibgroup价格
1条回答
网友
1楼 · 发布于 2024-09-30 05:15:05

因此,我想我可以帮助你用另一个更简单和工作的例子,适合你的需要

import pandas

df = pandas.DataFrame({
    'id': [1, 2, 3],
    'cat': ['cat_1', 'cat_2', 'cat_3'],
    'price': [1, 2, 3]
})

df.set_index(df['id'], drop=True, inplace=True)
new_df = pandas.DataFrame(index=df.index)

for var in df['cat'].unique():
    new_df[f'{var}_price'] = df[df['cat'] == var]['price']


new_df

输出:

    cat_1_price   cat_2_price   cat_3_price
id          
1    1.0             NaN             NaN
2    NaN             2.0             NaN
3    NaN             NaN             3.0

相关问题 更多 >

    热门问题