【问题标题】:For each loop on Pandas, each category对于 Pandas 上的每个循环,每个类别
【发布时间】:2019-10-10 13:15:17
【问题描述】:

我有一个问题。

我有一张这样的桌子

TAC | Latitude | Longitude
1 | 50.4 | -1.5 

在 Pandas 中,我想说:

对于每个 TAC,给我一个经纬度压缩列表(每个 TAC 可以有很多行)。

我尝试了以下类似的方法,但我做错了!你能帮忙吗?

df1['coordinates'] = list(zip(df1.Lat, df1.Long))
new_df = df1.iloc[ : , : ].groupby('TAC').agg(df1['coordinates'])

作为参考,DF1创建如下

df = pd.read_csv('tacs.csv')
df1 = df[['magnet.tac','magnet.latitude', 'magnet.longitude']]
df1.columns = ['TAC','Lat','Long']

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    首先添加usecols参数以避免SettingWithCopyWarning,然后将GroupBy.apply与lambda函数一起使用:

    df = pd.read_csv('tacs.csv', usecols=['magnet.tac','magnet.latitude', 'magnet.longitude'])
    df1.columns = ['TAC','Lat','Long']
    
    #sample data
    print (df1)
       TAC   Lat  Long
    0    1  50.4  -1.5
    1    1  50.1  -1.4
    2    2  50.2  -1.8
    3    2  50.9  -1.3
    
    new_df = df1.groupby('TAC').apply(lambda x: list(zip(x.Lat, x.Long))).reset_index(name='coord')
    print (new_df)
       TAC                         coord
    0    1  [(50.4, -1.5), (50.1, -1.4)]
    1    2  [(50.2, -1.8), (50.9, -1.3)]
    

    你的解决方案应该改变:

    df = pd.read_csv('tacs.csv')
    df1 = df[['magnet.tac','magnet.latitude', 'magnet.longitude']].copy()
    df1.columns = ['TAC','Lat','Long']
    
    df1['coordinates'] = list(zip(df1.Lat, df1.Long))
    new_df = df1.groupby('TAC')['coordinates'].agg(list).reset_index()
    

    【讨论】:

    • 谢谢。在这两种情况下,我都得到:/Users/keenek1/anaconda3/lib/python2.7/site-packages/ipykernel_launcher.py:1:SettingWithCopyWarning:试图在数据帧的切片副本上设置值。尝试改用 .loc[row_indexer,col_indexer] = value
    • @kikee1222 - 问题出在之前的代码中,df1 是如何创建的?
    • @kikee1222 - 在你的代码中需要.copy(),比如df1 = df[['magnet.tac','magnet.latitude', 'magnet.longitude']].copy(),但最好在这里使用usecols
    • 太感谢了。为什么需要.copy()?
    • @kikee1222 - 因为它修改了数据副本,请检查this
    猜你喜欢
    • 2012-12-18
    • 2013-11-22
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    • 2017-12-16
    • 1970-01-01
    相关资源
    最近更新 更多