无法将 python 数据帧中的一个可能拆分为两个



我有一个数据集如下。

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)

你必须指定你要分割的列和你要分割的列。如果您没有指定要拆分的字符/单词,则默认为"。

有关pd.Series.str.split()的其他信息,请访问官方文档。

要分割的字符串或正则表达式。如果未指定,则在空白处分割。

最新更新