python - Pandas 根据拆分另一列添加新列

标签 python pandas dataframe split multiple-columns

我有一个如下所示的 Pandas 数据框:

A              B
US,65,AMAZON   2016
US,65,EBAY     2016

我的目标是看起来像这样:

A              B      country    code    com
US.65.AMAZON   2016   US         65      AMAZON
US.65.AMAZON   2016   US         65      EBAY

我知道这个问题之前有人问过 herehere没有对我有用。我试过:

df['country','code','com'] = df.Field.str.split('.')

df2 = pd.DataFrame(df.Field.str.split('.').tolist(),columns = ['country','code','com','A','B'])

我错过了什么吗?非常感谢任何帮助。

最佳答案

您可以使用 split使用参数 expand=True 并在左侧添加一个 []:

df[['country','code','com']] = df.A.str.split(',', expand=True)

然后 replace :

df.A = df.A.str.replace(',','.')

print (df)
              A     B country code     com
0  US.65.AMAZON  2016      US   65  AMAZON
1    US.65.EBAY  2016      US   65    EBAY

如果没有 NaN 值,则使用 DataFrame 构造函数的另一种解决方案:

df[['country','code','com']] = pd.DataFrame([ x.split(',') for x in df['A'].tolist() ])
df.A = df.A.str.replace(',','.')
print (df)
              A     B country code     com
0  US.65.AMAZON  2016      US   65  AMAZON
1    US.65.EBAY  2016      US   65    EBAY

您也可以在构造函数中使用列名,但随后 concat是必要的:

df1=pd.DataFrame([x.split(',') for x in df['A'].tolist()],columns= ['country','code','com'])
df.A = df.A.str.replace(',','.')
df = pd.concat([df, df1], axis=1)
print (df)
              A     B country code     com
0  US.65.AMAZON  2016      US   65  AMAZON
1    US.65.EBAY  2016      US   65    EBAY

关于python - Pandas 根据拆分另一列添加新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38956778/

相关文章:

python - Django框架安装

Python、redis : How do I set multiple key-value pairs at once

python - Pandas 中的滚动差异

python - 在 Pandas 中 reshape 数据框

python - pygame 在退出()时仍然使用 .ttf 文件

python - PyCrypto 2.6 安装问题

python - pandas (sub)Dataframe 中的最大值和最小值

Python Pandas 更新/替换

r - 按多列对数据框行进行排序(排序)

r - 如何获得前 3 个值?