【发布时间】:2018-10-12 19:24:22
【问题描述】:
我有一个数据框,其中几列可能在单个观察中具有多个值。这些行中的每个观察在观察的末尾都有一个“/”,无论是否有多个。这意味着一些值看起来像这样:'OneThing/' 而其他值看起来像这样:'OneThing/AnotherThing/'
我需要在观察中获取多个值的值并将它们拆分为单独的行。
这是数据框以前外观的一般示例:
ID Date Name ColA ColB Col_of_Int ColC ColD
1 09/12 Ann String String OneThing/ String String
2 09/13 Pete String String OneThing/AnotherThing String String
3 09/13 Ann String String OneThing/AnotherThing/ThirdThing/ String String
4 09/12 Pete String String OneThing/ String String
我想要的输出是什么:
ID Date Name ColA ColB Col_of_Int ColC ColD
1 09/12 Ann String String OneThing String String
2 09/13 Pete String String OneThing String String
2 09/13 Pete String String Another Thing String String
3 09/13 Ann String String OneThing String String
3 09/13 Ann String String AnotherThing String String
3 09/13 Ann String String ThirdThing String String
4 09/12 Pete String String OneThing/ String String
我尝试了以下方法:
df = df[df['Column1'].str.contains('/')]
df_split = df[df['Column1'].str.contains('/')]
df1 = df_split.copy()
df2 = df_split.copy()
split_cols = ['Column1']
for c in split_cols:
df1[c] = df1[c].apply(lambda x: x.split('/')[0])
df2[c] = df2[c].apply(lambda x: x.split('/')[1])
new_rows = df1.append(df2)
df.drop(df_split.index, inplace=True)
df = df.append(new_rows, ignore_index=True)
这行得通,但我认为它会在每个“/”之后创建新行,这意味着 一个 正在为每个只有一个值的观察创建新行(我想要零个新行),并且为每个具有两个值(只需要一个)的观察创建两个新行,等等。
当观察中有三个或更多值时,这尤其令人沮丧,因为我得到了几个不必要的行。
有什么办法可以解决这个问题,以便只有不止一个的观察被添加到新行中?
【问题讨论】:
-
如果你的
df = pd.DataFrame({'Column1': ['OneThing/', 'TwoThing/AnotherThing/']}),你能给出预期的输出吗? -
@Ben.T 添加在上面!
标签: python python-3.x pandas split append