[英]How to add multiple data in single Row Column using pandas
我有一个 DataFrame,它有两列名为 Brand 和 con。
import pandas as pd
cars = {'Brand': ['Honda Civic','Toyota Corolla'],
'Con': [['India','Srilanka'],['India']]
}
df = pd.DataFrame(cars, columns = ['Brand', 'Con'])
print (df)
这给了我
Brand Con
0 Honda Civic [India, Srilanka]
1 Toyota Corolla [India]
我想将 dataframe 转换为此 output
Brand Con
0 [Honda Civic, Toyota Corolla] India
1 [Honda Civic] Srilanka
先感谢您:)
利用:
df.explode('Con').groupby('Con')['Brand'].agg(list).reset_index().reindex(df.columns, axis=1)
编辑:
cars = {'Brand': ['Honda Civic','Toyota Corolla'],
'Con': [['India','Srilanka'],['India']]
}
df = pd.DataFrame(cars, columns = ['Brand', 'Con'])
print (df)
from itertools import chain
df1 = pd.DataFrame({
'Con' : list(chain.from_iterable(df['Con'].tolist())),
'Brand' : df['Brand'].repeat(df['Con'].str.len())
})
df2 = df1.groupby('Con')['Brand'].agg(list).reset_index().reindex(df.columns, axis=1)
print(df2)
Brand Con
0 [Honda Civic, Toyota Corolla] India
1 [Honda Civic] Srilanka
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.