How to read multiple values in a column with a comma separator using python?

时间:2018-02-03 07:48:02

标签: python

how to read multiple values in a column with a comma separator using python ? Column 1 has numerical values, Column 2 has alphabets with comma separator.

col1 col2 11 a, b, c 22 d, e, f 33 g, h, i

2 个答案:

答案 0 :(得分:2)

If want new column of lists:

df['col3'] = df['col2'].str.split(',')

and if want new columns from column col2:

df = df.join(df.pop('col2').str.split(',', expand=True))

For dictionary need:

d1 = (df.set_index('col1')['col2']
       .str.split(',', expand=True)
       .stack()
       .reset_index(name='a')
       .groupby('a')['col1']
       .apply(list)
       .to_dict())
print (d1)
{'a': [11], 'b': [11], 'c': [11], 'd': [22], 
 'e': [22], 'f': [22], 'g': [33], 'h': [33], 'i': [33]}

答案 1 :(得分:1)

One way you could do it is make a data frame out of it using pandas.

df = pd.read_csv(file_path, names=["Col1", "Col2"], header=0, index_col=False)
for i in range(len(df)):
    numerical = df['Col1'][i]
    alpha = df['Col2'][i].split(sep=',')
    print("Numerical: " + str(numerical))
    print("AlphaN: ")
    for j in range(len(alpha)):
        print(alpha[j] + " ")