I have a Python Pandas dataframe.
I try to create a new column total_str
which is a list of the values in colA
and colB
.
This is the expected output :
colA colB total_str
0 ['a','b','c'] ['a','b','c'] ['a','b','c','a','b','c']
1 ['a','b','c'] nan ['a','b','c']
2 ['a','b','c'] ['d','e'] ['a','b','c','d','e']
#replace nan with empty list and then concatenate colA and colB using sum.
df['total_str'] = df.applymap(lambda x: [] if x is np.nan else x).apply(lambda x: sum(x,[]), axis=1)
df
Out[705]:
colA colB total_str
0 [a, b, c] [a, b, c] [a, b, c, a, b, c]
1 [a, b, c] NaN [a, b, c]
2 [a, b, c] [d, e] [a, b, c, d, e]
If there are other columns in the DF, you can use:
df['total_str'] = df.applymap(lambda x: [] if x is np.nan else x).apply(lambda x: x.colA+x.colB, axis=1)
chain
whill do this trick for you.
itertools.chain(*filter(bool, [colA, colB]))
this will return a iterator, if you need, you could use list
the result to get a list, such as
import itertools
def test(colA, colB):
total_str = itertools.chain(*filter(bool, [colA, colB]))
print list(total_str)
test(['a', 'b'], ['c']) # output: ['a', 'b', 'c']
test(['a', 'b', 'd'], None) # output: ['a', 'b', 'c']
test(['a', 'b', 'd'], ['x', 'y', 'z']) # ['a', 'b', 'd', 'x', 'y', 'z']
test(None, None) # output []
I assume that you want to deal with numpy.nan
and None
in your dataframe. You can simply write a helper function to replace them with empty list when creating the new columns. It's not clean but it works.
def helper(x):
return x if x is not np.nan and x is not None else []
dataframe['total_str'] = dataframe['colA'].map(helper) + dataframe['colB'].map(helper)
Use combine_first
for replace NaN
to empty list
for faster solution:
df['total_str'] = df['colA'] + df['colB'].combine_first(pd.Series([[]], index=df.index))
print (df)
colA colB total_str
0 [a, b, c] [a, b, c] [a, b, c, a, b, c]
1 [a, b, c] NaN [a, b, c]
2 [a, b, c] [d, e] [a, b, c, d, e]
df['total_str'] = df['colA'].add(df['colB'].combine_first(pd.Series([[]], index=df.index)))
print (df)
colA colB total_str
0 [a, b, c] [a, b, c] [a, b, c, a, b, c]
1 [a, b, c] NaN [a, b, c]
2 [a, b, c] [d, e] [a, b, c, d, e]
Timings :
df = pd.DataFrame({'colA': [['a','b','c']] * 3, 'colB':[['a','b','c'], np.nan, ['d','e']]})
#[30000 rows x 2 columns]
df = pd.concat([df]*10000).reset_index(drop=True)
#print (df)
In [62]: %timeit df['total_str'] = df['colA'].combine_first(pd.Series([[]], index=df.index)) + df['colB'].combine_first(pd.Series([[]], index=df.index))
100 loops, best of 3: 8.1 ms per loop
In [63]: %timeit df['total_str1'] = df['colA'].fillna(pd.Series([[]], index=df.index)) + df['colB'].fillna(pd.Series([[]], index=df.index))
100 loops, best of 3: 9.1 ms per loop
In [64]: %timeit df['total_str2'] = df.applymap(lambda x: [] if x is np.nan else x).apply(lambda x: x.colA+x.colB, axis=1)
1 loop, best of 3: 960 ms per loop
您可以像这样在熊猫中添加列:
dataframe['total_str'] = dataframe['colA'] + dataframe['colB']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.