【问题标题】:How to replicate data and replace values in one column?如何复制数据并替换一列中的值?
【发布时间】:2017-11-29 04:41:39
【问题描述】:

我正在使用这样的数据框:

samples  countries                 color   cost
a        US, UK, France, Germany   white   1.2
b        France, Germany           red     2.0
c        US                        blue    2.5

我想复制每个国家/地区的数据(只要有逗号),就变成:

samples  countries    color   cost
a        US           white   1.2
a        UK           white   1.2
a        France       white   1.2
a        Germany      white   1.2
b        France       red     2.0
b        Germany      red     2.0
c        US           blue    2.5

换句话说,我只想在有多个国家/地区时复制该行,同时保持其他列中的值相同。

如何使用 Pandas 做到这一点? 谢谢!

【问题讨论】:

标签: python pandas


【解决方案1】:

您可以将str.split 用于lists,然后将len 用于length

然后通过constructor 使用numpy.repeatnumpy.concatenate 创建新的DataFrame。列的最后更改顺序由reindex_axis 和最后由reset_index 使用参数drop=True 创建唯一索引:

#columns for repeat
cols = ['samples','color','cost']
splitted = df['countries'].str.split(',')
lens = splitted.str.len()

df = pd.DataFrame({x:np.repeat(df[x], lens) for x in cols}) \
       .assign(countries=np.concatenate(splitted)) \
       .reindex_axis(df.columns, axis=1) \
       .reset_index(drop=True)

print (df)
  samples countries  color  cost
0       a        US  white   1.2
1       a        UK  white   1.2
2       a    France  white   1.2
3       a   Germany  white   1.2
4       b    France    red   2.0
5       b   Germany    red   2.0
6       c        US   blue   2.5

【讨论】:

    【解决方案2】:

    您可以使用链式操作来做到这一点:

    首先拆分国家并将它们堆叠成行,然后将其连接回 df,删除旧国家列并使用新国家列。

    (
        df[df.columns.drop('countries')].join(df.countries.str.split(',')
                                                .apply(pd.Series).stack()
                                                .reset_index(1,drop=True)
                                                .to_frame()
                                                .rename(columns={0:'countries'}))
    )
    Out[67]: 
      samples  color cost countries
    0       a  white  1.2        US
    0       a  white  1.2        UK
    0       a  white  1.2    France
    0       a  white  1.2   Germany
    1       b    red  2.0    France
    1       b    red  2.0   Germany
    2       c   blue  2.5        US
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2021-01-04
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多