【发布时间】:2017-10-02 18:45:27
【问题描述】:
我将一个系列连接到一个数据框中,但列名称(系列名称)未显示在新数据框上。
相反,该列在最终数据帧中的名称为“0”,但在 apply_join 方法中创建时,该名称确实出现了。
为什么在数据框中看不到系列名称?
import pandas as pd
from io import StringIO
tibble3_csv = """country,year,cases,population
Afghanistan,1999,745,19987071
Afghanistan,2000,2666,20595360"""
with StringIO(tibble3_csv) as fp:
tibble3 = pd.read_csv(fp)
def str_join_elements(x, sep=""):
assert type(sep) is str
return sep.join((str(xi) for xi in x))
def unite(df, cols, new_var, combine=str_join_elements):
def apply_join(x, combine):
joinstr = combine(x)
ser = pd.Series(joinstr, name=new_var)
print(ser.name)
return ser
fixed_vars = df.columns.difference(cols)
tibble = df[fixed_vars].copy()
tibble_extra = df[cols].apply(apply_join, combine=combine, axis=1)
return pd.concat([tibble, tibble_extra], axis=1)
tab = unite(tibble3, ['cases', 'population'], 'rate', combine=lambda x: str_join_elements(x, "/"))
print(tab)
结果:
rate
rate
country year 0
0 Afghanistan 1999 745/19987071
1 Afghanistan 2000 2666/20595360
【问题讨论】:
标签: python pandas dataframe series