转置表格
Transposing tables
我是 python 的初学者,正在尝试转置以下内容 table:
Column1 Column2
x 3
y 4
我期待以下输出:
x
x
x
y
y
y
y
获得此输出的最佳方法是什么?
a = [3, 4]
b = ['cheese', 'corn']
c = [(b + ' ')*a for a, b in zip(a,b)]
d = [element.split() for element in c]
array = np.array([item for sublist in c for item in sublist])
现在您将拥有一个包含字符串副本的数组。
我不确定你的 table 使用的是什么数据结构,但如果你有 pandas DataFrame,你可以创建一个扁平化列表,如下所示。
输入:
df = pd.DataFrame([['x', 3], ['y', 4]], columns=['col1', 'col2'])
df
输出:
col1 col2
x 3
y 4
输入:
flattened_table = []
for index, row in df.iterrows():
flattened_table += (row.values[0] * row.values[1])
flattened_table
输出:
['x', 'x', 'x', 'y', 'y', 'y', 'y']
我是 python 的初学者,正在尝试转置以下内容 table:
Column1 Column2
x 3
y 4
我期待以下输出:
x
x
x
y
y
y
y
获得此输出的最佳方法是什么?
a = [3, 4]
b = ['cheese', 'corn']
c = [(b + ' ')*a for a, b in zip(a,b)]
d = [element.split() for element in c]
array = np.array([item for sublist in c for item in sublist])
现在您将拥有一个包含字符串副本的数组。
我不确定你的 table 使用的是什么数据结构,但如果你有 pandas DataFrame,你可以创建一个扁平化列表,如下所示。
输入:
df = pd.DataFrame([['x', 3], ['y', 4]], columns=['col1', 'col2'])
df
输出:
col1 col2
x 3
y 4
输入:
flattened_table = []
for index, row in df.iterrows():
flattened_table += (row.values[0] * row.values[1])
flattened_table
输出:
['x', 'x', 'x', 'y', 'y', 'y', 'y']