【问题标题】:Can't split the of one coulmn in a python dataframe into two无法将 python 数据框中的一列拆分为两列
【发布时间】:2021-07-26 04:50:36
【问题描述】:

我有如下数据集。

df=
0    153.38 -27.99
1    151.21 -33.87
2    151.21 -33.87
3    153.05 -26.68
4    153.44 -28.06
Name: merchant_long_lat, dtype: object

当我实现拆分代码以将lat-long 拆分为两个不同的列时,分别命名为latlong,即:

df[['merch_long','merch_lat']]=df.str.split(expand=True)

它返回一个错误为:

ValueError                                Traceback (most recent call last)
/tmp/ipykernel_1821133/1587686441.py in <module>
----> 1 df[['merch_long','merch_lat']]=df.str.split(expand=True)

~/.local/lib/python3.8/site-packages/pandas/core/indexers.py in check_key_length(columns, key, value)
    426     if columns.is_unique:
    427         if len(value.columns) != len(key):
--> 428             raise ValueError("Columns must be same length as key")
    429     else:
    430         # Missing keys in columns are represented as -1

ValueError: Columns must be same length as key

【问题讨论】:

  • 试试,df.merchant_long_lat.str.split(expand=True)??
  • @Samar this 能解决您的问题吗?如果它解决了您的问题,请不要忘记将此标记为已接受的答案。

标签: python pandas dataframe data-processing


【解决方案1】:

你正在尝试这样做:

df[['merch_long','merch_lat']]=df.merchant_long_lat.str.split(" -",expand=True)

您必须指定要拆分的列以及拆分的内容。如果您没有指定要拆分的字符/单词,则默认为“”。

有关pd.Series.str.split()的其他信息,您可以访问official documentation

要拆分的字符串或正则表达式。如果未指定,则以空格分隔。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 2022-01-20
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    相关资源
    最近更新 更多