【问题标题】:How to divide the column 'location' in given data frame?如何划分给定数据框中的“位置”列?
【发布时间】:2023-03-17 13:26:01
【问题描述】:

我正在处理一个数据集,其中列被命名为标题。值如前所述。

df = pd.DataFrame(data={"location":["düsseldorf, nordrhein-westfalen, germany",
                                    "durbanville , cape town, cape town , south africa"]})

我想把这个专栏分成['city', 'state', 'country']。注意第二行有重复。

我已经尝试了以下方法,但这并不处理重复:

location = df.location.str.split(', ', n=2, expand=True)

location.columns = ['city', 'state', 'country']

【问题讨论】:

  • 你想要的输出是什么?你试过什么?
  • location=df.location.str.split(', ', n=2, expand=True) location.columns=['city', 'state', 'country']
  • 但我无法处理重复问题

标签: python string python-3.x pandas dataframe


【解决方案1】:

你可以限制自己只用pandas来处理这个问题:

import pandas as pd

pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None) 

data_all=(['düsseldorf', 'nordrhein-westfalen', 'germany', 'durbanville', 'cape town', 'south africa'])
dfe = [[], [], []]

i = 0
j = 1
k = 2

while i < len(data_all):
  dfe[0].append(data_all[i])
  i += 3
while j < len(data_all):
  dfe[1].append(data_all[j])
  j += 3
while k < len(data_all):
  dfe[2].append(data_all[k])
  k += 3

d = {'city': dfe[0], 'state': dfe[1], 'country': dfe[2]}
df = pd.DataFrame(data=d)
print(df)

结果:

          city                state       country
0   düsseldorf  nordrhein-westfalen       germany
1  durbanville            cape town  south africa

但实际上我不明白为什么要使用重复项,如果您只有 3 列:城市、州和国家/地区。

【讨论】:

    【解决方案2】:

    您可以使用itertools docs 中提供的unique_everseen 配方,该配方也可在toolz.unique 等第三方库中使用。

    该逻辑可以合并到迭代df['location'] 的列表推导中。这可能比 Pandas 基于字符串的方法更有效,后者不提供矢量化功能。

    from toolz import unique
    
    res = pd.DataFrame([list(unique(map(str.strip, i.split(',')))) for i in df['location']])
    
    res.columns = ['city', 'state', 'country']
    
    print(res)
    
              city                state       country
    0   düsseldorf  nordrhein-westfalen       germany
    1  durbanville            cape town  south africa
    

    【讨论】:

      猜你喜欢
      • 2020-08-04
      • 2023-04-08
      • 2021-04-17
      • 2021-10-01
      • 2023-03-08
      • 1970-01-01
      • 2022-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多