无法将 python 数据框中的一列拆分为两列

Can't split the of one coulmn in a python dataframe into two

我有如下数据集。

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[['merch_long','merch_lat']]=df.merchant_long_lat.str.split(" -",expand=True)

您必须指定要拆分的列以及拆分的对象。如果您没有指定要拆分的 character/word,则默认为“”。

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

String or regular expression to split on. If not specified, split on whitespace.