如何将两列连接到Pandas的另一个独立列中?

时间:2018-11-07 21:28:52

标签: python pandas

任何帮助将不胜感激。这可能很容易,但是对Python来说是新手。
我想添加两个列,即纬度和经度,并将其放入名为位置的列中。

例如:

“纬度”的第一行的值为41.864073,经度的第一行的值为-87.706819

我希望'Locations'列显示41.864073, -87.706819

请谢谢你。

4 个答案:

答案 0 :(得分:2)

我对此列的用途表示怀疑,但是您可以通过在列上应用tuple来调用它。

>>> df = pd.DataFrame([[1, 2], [3,4]], columns=['lon', 'lat'])
>>> df
>>> 
   lon  lat
0    1    2
1    3    4
>>> 
>>> df['Location'] = df.apply(tuple, axis=1)
>>> df
>>> 
   lon  lat Location
0    1    2   (1, 2)
1    3    4   (3, 4)

如果数据框中除了'lon''lat'之外还有其他列,请使用

df['Location'] = df[['lon', 'lat']].apply(tuple, axis=1)

答案 1 :(得分:2)

Pir中的数据

df['New']=tuple(zip(*df[['lat','lon']].values.T))
df
Out[106]: 
   lat  lon        New
0   10  100  (10, 100)
1   11  101  (11, 101)
2   12  102  (12, 102)
3   13  103  (13, 103)
4   14  104  (14, 104)
5   15  105  (15, 105)
6   16  106  (16, 106)
7   17  107  (17, 107)
8   18  108  (18, 108)
9   19  109  (19, 109)

答案 2 :(得分:1)

设置

df = pd.DataFrame(dict(lat=range(10, 20), lon=range(100, 110)))

zip

这应该比使用apply

更好
df.assign(location=[*zip(df.lat, df.lon)])

   lat  lon   location
0   10  100  (10, 100)
1   11  101  (11, 101)
2   12  102  (12, 102)
3   13  103  (13, 103)
4   14  104  (14, 104)
5   15  105  (15, 105)
6   16  106  (16, 106)
7   17  107  (17, 107)
8   18  108  (18, 108)
9   19  109  (19, 109)

list变体

尽管我仍然建议tuple

df.assign(location=df[['lat', 'lon']].values.tolist())

   lat  lon   location
0   10  100  [10, 100]
1   11  101  [11, 101]
2   12  102  [12, 102]
3   13  103  [13, 103]
4   14  104  [14, 104]
5   15  105  [15, 105]
6   16  106  [16, 106]
7   17  107  [17, 107]
8   18  108  [18, 108]
9   19  109  [19, 109]

答案 3 :(得分:0)

我肯定从W-B和timgeb学到了一些东西。我的想法是只转换为字符串并进行连接。如果您希望将结果作为字符串,我会发布我的答案。否则,看起来上面的答案是正确的方法。

import pandas as pd
from pandas import *  

Dic = {'Lattitude': [41.864073], 'Longitude': [-87.706819]}
DF = pd.DataFrame.from_dict(Dic)
DF['Location'] = DF['Lattitude'].astype(str) + ',' +  DF['Longitude'].astype(str)