python - 如何从 Pandas 中的两列形成元组列

标签 python dataframe pandas tuples

我有一个 Pandas DataFrame,我想将 'lat' 和 'long' 列组合成一个元组。

<class 'pandas.core.frame.DataFrame'>
Int64Index: 205482 entries, 0 to 209018
Data columns:
Month           205482  non-null values
Reported by     205482  non-null values
Falls within    205482  non-null values
Easting         205482  non-null values
Northing        205482  non-null values
Location        205482  non-null values
Crime type      205482  non-null values
long            205482  non-null values
lat             205482  non-null values
dtypes: float64(4), object(5)

我尝试使用的代码是:

def merge_two_cols(series): 
    return (series['lat'], series['long'])

sample['lat_long'] = sample.apply(merge_two_cols, axis=1)

但是,这会返回以下错误:

---------------------------------------------------------------------------
 AssertionError                            Traceback (most recent call last)
<ipython-input-261-e752e52a96e6> in <module>()
      2     return (series['lat'], series['long'])
      3 
----> 4 sample['lat_long'] = sample.apply(merge_two_cols, axis=1)
      5

...

AssertionError: Block shape incompatible with manager 

我该如何解决这个问题?

最佳答案

熟悉 zip。在处理列数据时它会派上用场。

df['new_col'] = list(zip(df.lat, df.long))

它比使用 applymap 更简单、更快捷。像 np.dstack 这样的东西比 zip 快两倍,但不会给你元组。

关于python - 如何从 Pandas 中的两列形成元组列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16031056/

相关文章:

dataframe - 重命名数据帧pyspark中的列添加字符串

python - 计算数据框中每个列值的顺序百分比

python - 使用文本文档更改列表中的项目

Python 十进制自定义上下文

python - 无意义的空间名词

Python - 将数据框中的所有项目转换为字符串

python - 为什么我的 python 合并排序实现只返回具有最小项目的单例列表?

r - 如何根据R中的group_by函数对列中的所有独特因素求和并输出为新列?

python - 按 GroupBy 内容过滤 Pandas DataFrame

python - 根据 Pandas 中另一列的状态创建一个新列