Python 对于熊猫上的每个循环,每个类别
我有个问题 我有一张这样的桌子Python 对于熊猫上的每个循环,每个类别,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有个问题 我有一张这样的桌子 TAC | Latitude | Longitude 1 | 50.4 | -1.5 在《熊猫》中,我想说: 对于每个TAC,给我一个纬度和经度的压缩列表(每个TAC可以有许多行) 我试过下面的方法,但我做错了!你能帮忙吗 df1['coordinates'] = list(zip(df1.Lat, df1.Long)) new_df = df1.iloc[ : , : ].groupby('TAC').agg(df1['coordinates']) 作为参
TAC | Latitude | Longitude
1 | 50.4 | -1.5
在《熊猫》中,我想说:
对于每个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']
首先添加用于避免的
usecols
参数,然后与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\u indexer,col\u indexer]=valueinstead@kikee1222-问题是在以前的代码中,如何创建
df1
?@kikee1222-在您的r代码中需要.copy()
像df1=df[['magnet.tac'、'magnet.lation'、'magnet.lation'、'magnet.longitude']].copy()
,但更好的是使用usecols
,谢谢您的工作。为什么它需要.copy()?@kikee1222-因为它修改了数据的副本,请检查